串口通讯控制舵机问题
本人新手,想要通过串口通讯的方式来对舵机进行控制,但是遇到了2个问题,百度了很久也没有找到解决方法,请教一下各位大神。问题1:比如初始角度设定为140,串口输入100,舵机会转到100度但马上又会转回140度,不知为何
问题2:在输入过一次角度后,之后再输入角度就没有反应了,如果把COM窗口关了再开有的时候可以再输,有的时候不行。
本人开发板是arduino mega2560 电脑是win8.谢谢大家! 代码如下:
#include<Servo.h>
Servo steer1;
static int angle1 = 140;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
steer1.attach(7);
steer1.write(angle1);
}
void loop() {
Serial.println(angle1);
steer1.write(angle1);
int num = 0;
char c2 = 0;
int i = 3;
while (i > 0)
{
if (Serial.available() > 0)
{
Serial.println('b');
c2 = Serial.read();
Serial.println(c2);
if (c2 <= '9' && c2 >= '0')
{
if (i == 3)
{
num += 100 * (c2 - '0');
}
else if (i == 2)
{
num += 10 * (c2 - '0');
}
else
{
num += c2 - '0';
}
i--;
}
}
}
angle1 = num;
}
0到255的值用一个char传就可以了 不要这么麻烦,直接用Serial.parselnt能直接读出整数值!!
页:
[1]