制作需要:用AppInventor制作App,小车硬件以Arduino Nano为主控板,接蓝牙模块,超声波模块,两个直流电机。
功能:用手机App控制小车前进,后退,左转,右转,自动避障,并且可以通过滑动条调速。(其中自动巡线功能暂时未完成)
Arduino编程参考手册:
http://wiki.dfrobot.com.cn/index.php/Arduino%E7%BC%96%E7%A8%8B%E5%8F%82%E8%80%83%E6%89%8B%E5%86%8C
AppInventor在线编辑器:
http://app.gzjkw.net/login/
App图标:
APP界面:
小车实物:
App代码:
小车代码(Arduino):
#include <Arduino.h>int MotorL(int speeed);
int MotorR(int speeed);
void Forward();
void Backward();
void TurnLeft();
void TurnRight();
void Stop();
int Distance(); //超声波测距
void left_or_back(bool x);//0-左转,1-后退
int mode = 0;//0-按钮控制,1-自动避障
int moveSpeed = 125;
int turnSpeed = 0;
int distance=0;
unsigned long start_time = 0;
unsigned long end_time = 0;
const int TrigPin = 11;
const int EchoPin = 12;void setup() {Serial.begin(9600);pinMode(TrigPin,OUTPUT);pinMode(EchoPin,INPUT);pinMode(6, OUTPUT); pinMode(7, OUTPUT); pinMode(3, OUTPUT); pinMode(5, OUTPUT); Stop();//停车start_time = millis();
}void loop() {if(mode == 1){int cm = Distance();if(cm>20){ //大于20CM直走Forward(); //直走}else if(cm>=0 && cm<=10){Stop();left_or_back(0);left_or_back(1);}}if(Serial.available()>0){int ch = Serial.read();if(ch>=0 && ch<=100){moveSpeed=int(ch*2.15+40);}else if(ch == 105){mode = 1;}else{switch(ch){case 101:Forward();break;//前进case 102:Backward();break;//后退case 103:TurnLeft();break;//左转case 104:TurnRight();break;//右转case 111:Stop();break;//停车default:break;}mode = 0;}}
}
void left_or_back(bool x){start_time = millis();end_time = millis();while(end_time - start_time < 500){end_time = millis();x ? TurnLeft() : Backward();//后退if(Serial.available()>0){int ch = Serial.read();if(ch!=105){mode = 0;Stop();break;}}}
}
int Distance() //超声波测距
{digitalWrite(TrigPin,LOW);delayMicroseconds(2);digitalWrite(TrigPin,HIGH);delayMicroseconds(10);digitalWrite(TrigPin,LOW);int cm=pulseIn(EchoPin,HIGH)/58;return cm;
}
int MotorL(int speeed)
{ analogWrite(5, speeed);}int MotorR(int speeed)
{analogWrite(3, speeed);}void Forward()
{digitalWrite(6, LOW);digitalWrite(7, LOW);MotorL(moveSpeed);MotorR(moveSpeed);
}
void Backward()
{ digitalWrite(6,HIGH);digitalWrite(7,HIGH);MotorL(moveSpeed);MotorR(moveSpeed);
}
void TurnLeft()
{ digitalWrite(6, LOW);digitalWrite(7, HIGH);MotorL(moveSpeed);MotorR(moveSpeed);
}
void TurnRight()
{digitalWrite(6, HIGH);digitalWrite(7, LOW);MotorL(moveSpeed);MotorR(moveSpeed);
}
void Stop()
{MotorL(0);MotorR(0);
}