/*注意事项:(在烧写的过程中,请先断开蓝牙模块和Nano板的连接,否则会烧不进程序。)
1.写代码到Arduino板上时,数字0和1口不能接线,必需拨掉(不要带电拨线,容易烧)
2.蓝牙的TX口接Arduino板上的0口,RX口接Arduino板上的1口
*/
#include <Servo.h> // 声明调用Servo.h库
Servo myservo; // 创建一个舵机对象
int pos = 0;
// 变量pos用来存储舵机位置
void setup() {
Serial.begin(9600); //串口波特率(使用蓝牙串口必需此句)
//舵机引出三根线。一根是红色,连到+5V上。一根棕色(有些是黑的),连到GND。
//还有一根是黄色或者橘色,连到数字引脚9。
myservo.attach(9); // 将引脚9上的舵机与声明的舵机对象连接起来
}
void loop() {
while(Serial.available()) //判断缓冲器状态。
{
char c=Serial.read(); //读取串口
if(c=='A') //判断串口是否等于A
{
for(pos = 0; pos < 180; pos += 1){ // 舵机从0°转到180°,每次增加1°
myservo.write(pos); // 给舵机写入角度
delay(15); // 延时15ms让舵机转到指定位置
}
Serial.println("LEFT");// 串口输出数据并带回车符。
}
if(c=='B') //判断串口是否等于B
{
for(pos = 180; pos>=1; pos-=1) { // 舵机从180°转回到0°,每次减小1°
myservo.write(pos); // 写角度到舵机
delay(15); // 延时15ms让舵机转到指定位置
}
Serial.println("RIGHT");// 串口输出数据并带回车符。
}
}
}
|