智能小車開發實作(2)-功能調試-手機app藍芽控制小車四方移動
智能小車開發實作(2)-功能調試-手機app藍芽控制小車四方移動
今天要來實作手機藍芽控制小車移動。以前覺得這個對我來說有點
不難,可能要搞很久,沒想到今天二小時就搞定,首先思路上,要
先懂得如何配對藍芽,這次我用的是BT-06這款藍芽模組,和HC-06
一樣,可以回顧這篇HC-06藍芽模組實習。配對和測試好之後,大概
就是在之前調試的程式碼再加上藍芽監測和發送手機app發送溝通的
對應字串讓小車移動。
app開發調控其實也不難,對於簡單的控制部份,我覺得只要先學會
藍芽連線,斷線的請求,控制的部份就是設定對應的字串來溝通。
程式碼:
#include <SoftwareSerial.h>
SoftwareSerial BTserial(3, 4);
char val;
int E1 = 10; //pwm
int M1 = 12;
int E2 = 11; //pwm
int M2 = 13;
//R_speed & L_speed 0~255
void forward(byte R_SPEED, byte L_SPEED)
{
analogWrite(E1, R_SPEED);
analogWrite(E2, L_SPEED);
digitalWrite(M1, HIGH);
digitalWrite(M2, HIGH);
delay(50);
}
void back(byte R_SPEED, byte L_SPEED)
{
analogWrite(E1, R_SPEED);
analogWrite(E2, L_SPEED);
digitalWrite(M1, LOW);
digitalWrite(M2, LOW);
delay(50);
}
void right(byte R_SPEED, byte L_SPEED){
analogWrite(E1, R_SPEED);
analogWrite(E2, L_SPEED);
digitalWrite(M1, HIGH);
digitalWrite(M2, LOW);
delay(50);
}
void left(byte R_SPEED, byte L_SPEED){
analogWrite(E1, R_SPEED);
analogWrite(E2, L_SPEED);
digitalWrite(M1, LOW);
digitalWrite(M2, HIGH);
delay(50);
}
void stop(byte R_SPEED, byte L_SPEED)
{
analogWrite(E1, R_SPEED);
analogWrite(E2, L_SPEED);
digitalWrite(M1, HIGH);
digitalWrite(M2, HIGH);
// delay(50);
}
void setup()
{
BTserial.begin(9600);
pinMode(M1, OUTPUT);
pinMode(M2, OUTPUT);
}
void loop()
{
if (BTserial.available()){
val=BTserial.read();
if (val=='0'){
stop(0, 0);
}else if (val=='1'){
forward(100, 100);
}else if (val=='2'){
back(100, 100);
}else if (val=='3'){
left(70, 100);
}else if (val=='4'){
right(100, 70);
}
}
}
留言
張貼留言