通过C控制电机

时间:2013-11-05 01:08:00

标签: c nxt

我正在开发一款NXT乐高头脑风暴机器人,我正在用单反射光传感器构建线跟随器,我用C语言编程。

传感器将原始模拟值转换为数字值,范围为0 - 1023。

我必须编码线是黑色然后电机将向前移动,如果没有线(白色底座)然后停止,如果有灰色(在白线和黑线之间)然后稍微向右移动然后不同地找到丢失的黑线。

所以代码就像

While (1)
{
a=ecrobot_get_light_sensor(port_led); //storing the A/D converted value in variable

while (a<300)   // White area
{
ecrobot_status_monitor("White Area");
nxt_motor_set_speed(port_motor_l, 0, 1); // left motor turns off
nxt_motor_set_speed(port_motor_r, 0, 1); // right motor turns off
}
while (a>=600) // Black Line
{
ecrobot_status_monitor("Black Area");
nxt_motor_set_speed(port_motor_l, 100, 1); // left motor turns on
nxt_motor_set_speed(port_motor_r, 100, 1); // right motor turns on
}

while (a>=300 || a<600) // Robot loosing the black line
{
ecrobot_status_monitor("grey Area");
nxt_motor_set_speed(port_motor_l, 50, 1); // left motor move forward
nxt_motor_set_speed(port_motor_r, -50, 1); // right motor move backward

delay_ms(200)
nxt_motor_set_speed(port_motor_l, -50, 1); // left motor move backward
nxt_motor_set_speed(port_motor_r, 50, 1); // right motor move forward
delay_ms(200)

}

问题是如果机器人失去线路,则开始顺时针方向移动而不停止,并在延迟200 ms后逆时针移动。

我的代码有什么问题?

如何在此间隔后停止电机,电机应在此间隔后沿其他方向移动以寻找线路,然后它肯定会找到一条线

谢谢!

2 个答案:

答案 0 :(得分:1)

一种解决方案是将while(1)循环中的所有while语句更改为if语句。

例如,在你的最后一个声明中,当机器人失去黑线时,你的机器人将顺时针旋转,然后在每个方向逆时针旋转200ms ,无论从下面读取新值你的传感器。这是因为最后一个while语句将在 a 更新之前完成其执行。

答案 1 :(得分:0)

我看到了几件事,

  • 有些分号丢失。我确定在您的真实代码中不是这种情况,因为它甚至不会编译。也请在你的陈述中尝试使用正确的括号(更好的做法:-)

  • 您还需要在循环中重新读取传感器以避免死锁!!!

  • 同样如上所述,在一个大的while循环中使用if / else if语句。

  • 您可以添加一些阈值以使其更流畅: - )

祝你好运