---
# System prepended metadata

title: 藍芽車載測試程式
tags: [Arduino 實作, Arduino]

---

###### tags: `Arduino` `Arduino 實作`
# 藍芽車載測試程式
```cpp=
const int EN[2] = {10,5};
const int mt[4] = {9,8,7,6};
#include<SoftwareSerial.h>
SoftwareSerial BT(3,2);
char val;

//----------------------車子控制-------------------
void forward(){
  digitalWrite(mt[0],0);
  digitalWrite(mt[1],1);
  digitalWrite(mt[2],0);
  digitalWrite(mt[3],1);
  analogWrite(EN[0],255);
  analogWrite(EN[1],255);
  delay(200);
  sm();
}
void backward(){
  digitalWrite(mt[0],1);
  digitalWrite(mt[1],0);
  digitalWrite(mt[2],1);
  digitalWrite(mt[3],0);
  analogWrite(EN[0],255);
  analogWrite(EN[1],255);
  delay(200);
  sm();
}
void right(){
  digitalWrite(mt[0],0);
  digitalWrite(mt[1],1);
  digitalWrite(mt[2],1);
  digitalWrite(mt[3],0);
  analogWrite(EN[0],255);
  analogWrite(EN[1],255);
  delay(200);
  sm();
}
void left(){
  digitalWrite(mt[0],1);
  digitalWrite(mt[1],0);
  digitalWrite(mt[2],0);
  digitalWrite(mt[3],1);
  analogWrite(EN[0],255);
  analogWrite(EN[1],255);
  delay(200);
  sm();
}
void sm(){
  digitalWrite(mt[0],0);
  digitalWrite(mt[1],0);
  digitalWrite(mt[2],0);
  digitalWrite(mt[3],0);
  analogWrite(EN[0],0);
  analogWrite(EN[1],0);
}

void test(){
  digitalWrite(mt[0],0);
  digitalWrite(mt[1],1);
  digitalWrite(mt[2],0);
  digitalWrite(mt[3],1);
  analogWrite(EN[0],-255);
  analogWrite(EN[1],-255);
}

//------------------------------------------------

void setup() {
  pinMode(5,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(10,OUTPUT);
  BT.begin(9600);
  Serial.begin(9600);
}
void loop() {
  if(BT.available()){
    val = BT.read();
    Serial.print(val);
    switch(val){
      case 'w':
        forward();
        break;
      case 'a':
        left();
        break;
      case 's':
        backward();
        break;
      case 'd':
        right();
        break;
      case 'o':
        test();
        break;
    }
  }
}
```