Arduino nano作为主控板,控制由四个SG90舵机组成的机械臂,原先想着用四个电位计控制舵机转动,结果舵机一直抖动,索性就使用串口类似at指令控制舵机转动。使用的串口中断,通信的数据也是 字母+数字 的格式,字母代表舵机的编号,目前只控制三个舵机,对应的字母分别是 a,s,d,数字代表需要转动到的角度。
以下是代码。
#include <Servo.h>Servo myservo;
Servo myservo1;
Servo myservo2;int angle = 60;
int angle1 = 140;
int angle2 = 80;boolean stringComplete = false;void setup()
{Serial.begin(9600);myservo.attach(2);myservo1.attach(3);myservo2.attach(4);myservo.write(angle);myservo1.write(angle1);myservo2.write(angle2);
}void loop()
{if (stringComplete) {myservo.write(angle);myservo1.write(angle1);myservo2.write(angle2);Serial.print("angle:");Serial.println(angle);Serial.print("angle1:");Serial.println(angle1);Serial.print("angle2:");Serial.println(angle2);Serial.println();stringComplete = false;}}void serialEvent() {char inChar = (char)Serial.read();if (inChar == 'a'){angle = Serial.parseInt();stringComplete = true;}if (inChar == 's'){angle1 = Serial.parseInt();stringComplete = true;}if (inChar == 'd'){angle2 = Serial.parseInt();stringComplete = true;}
}