藍牙控制——智走車

藍牙功能:利用藍牙調試串口,進行命令的設置,當接收到特定指令時,就能控制行李箱的行動軌跡,
當藍牙串口發送1時前進,發送2時後退,發送3時左轉,發送4時右轉,發送8進入跟隨模式,發送其它數據則停下。

#include <SoftwareSerial.h>
#define RxD 2 //BlueToothSerial D2 //藍牙模擬
#define TxD 3 //BlueToothSerial D3//藍牙模擬UART
#define motorIn1 6
#define motorIn2 8
#define motorIn3 5
#define motorIn4 7
SoftwareSerial blueToothSerial(RxD,TxD); //設定模擬UART
unsigned char Motion_val=0;
float distance; //距離變量
float temp;

byte SPEED1 = 15;
byteSPEED2=20;
int Fspeedd = 0; // 前速
int Rspeedd = 0; // 右速
int Lspeedd = 0; // 左速
int directionn = 0;
int Fgo = 8; // 前進
int Rgo = 6; // 右轉
int Lgo = 4; // 左轉
int Bgo = 2; // 後退
int sgo=1;
const int DELAY = 1000;
void setup()
{
pinMode(motorIn1, OUTPUT);
pinMode(motorIn2, OUTPUT);
pinMode(motorIn3, OUTPUT);
pinMode(motorIn4, OUTPUT);
pinMode(Echo, INPUT);
Serial.begin(9600);

//Serial.begin(38400);//硬件串口
blueToothSerial.begin(38400);//軟件串口波特率
Serial.print(“lanya4.0”);
blueToothSerial.print(“AT”);
}
void loop()
{
BLUETOOTH_Control();//藍牙遙控

}
void BLUETOOTH_Control()
{if(blueToothSerial.available()>0)//available()用來判斷串口緩衝區是否有數據輸入
{
char Receive_val=blueToothSerial.read();//將藍牙串口讀取到的數據放入Receive_val
Serial.print(Receive_val);//通過硬件串口監視器顯示藍牙發過來的數據
if(Receive_val==‘1’)
{
forward(0);
Serial.print(" Forward “);
}else if(Receive_val==‘2’)
{
backward(0);
Serial.print(” backward ");
}else if(Receive_val==‘3’)
{
left(0);
delay(800);
motorstop(0);
delay(1000);
forward(0);
Serial.print("Left ");
}else if(Receive_val==‘4’)
{
right(0); // 右轉
delay(800);
motorstop(0);
delay(1000);
forward(0);
Serial.print("rigth “);
}else if(Receive_val==‘8’)
{
fallow_up();
}else
{
motorstop(0);
} }
}
void fallow_up()
{
detection();
if(directionn == Rgo)
{
right(0); // 右轉
delay(800);
motorstop(0);
delay(1000);
forward(0);
}
if(directionn == Lgo)
{
left(0);
delay(800);
motorstop(0);
delay(1000);
forward(0); }
if(directionn == Fgo)
{
forward(0); // 正常前進
Serial.print(” Forward “);
}
if(directionn == sgo)
{
motorstop(0); // 正常前進
Serial.print(” motorstop ");
}}

}
//馬達部分
void motorstop(int a)
{
digitalWrite(motorIn1, LOW);
digitalWrite(motorIn2, LOW);
digitalWrite(motorIn3, LOW);
digitalWrite(motorIn4, LOW);
delay(a100);
}
void forward(int b)
{
digitalWrite(motorIn1,SPEED1 );
digitalWrite(motorIn2, LOW);
digitalWrite(motorIn3,SPEED2);
digitalWrite(motorIn4, LOW);
delay(b
100);
}
void backward(int c)
{
digitalWrite(motorIn1, LOW);
digitalWrite(motorIn2, HIGH);
digitalWrite(motorIn3, LOW);
digitalWrite(motorIn4, HIGH);
delay(c100);
}
// Let right motor keep running, but stop left motor
void right(int d)
{
digitalWrite(motorIn1, HIGH);
digitalWrite(motorIn2, LOW);
digitalWrite(motorIn3, LOW);
digitalWrite(motorIn4, LOW);
delay(d
100);
}
// Let left motor keep running, but stop right motor
void left(int e)
{
digitalWrite(motorIn1, LOW);
digitalWrite(motorIn2, LOW);
digitalWrite(motorIn3, HIGH);
digitalWrite(motorIn4, LOW);
delay(e*100);
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章