2

我想将我的机器人移动一定数量的步数,然后让它停止。然而,循环似乎无限运行。我使用 void loop() 的方式或者我编写“for”循环的方式是否有错误?

    // walkerForward.pde - Two servo walker. Forward.
// (c) Kimmo Karvinen & Tero Karvinen http://BotBook.com
// updated - Joe Saavedra, 2010
#include <Servo.h> 

Servo frontServo;  
Servo rearServo;  
int centerPos = 90;
int frontRightUp = 75;
int frontLeftUp = 120;
int backRightForward = 45;
int backLeftForward = 135;

void moveForward(int steps)
{
  for (int x = steps; steps > 0; steps--) {
    frontServo.write(centerPos);
    rearServo.write(centerPos);
    delay(100);
    frontServo.write(frontRightUp);
    rearServo.write(backLeftForward);
    delay(100);
    frontServo.write(centerPos);
    rearServo.write(centerPos);
    delay(100);
    frontServo.write(frontLeftUp);
    rearServo.write(backRightForward);
    delay(100);
  }
}


void setup()
{
  frontServo.attach(2);
  rearServo.attach(3);
}

void loop()
{
    moveForward(5);
}
4

2 回答 2

1

loop()函数在无限循环中执行(如果您检查 Arduino IDE 附带的主 cpp 文件,您会看到如下内容:

int main()
{
    setup();
    for (;;) {
        loop();
    }
    return 0;
}

因此,要么调用你的moveForward()函数setup()并创建loop()一个空函数,要么exit(0);loop()after内部调用moveForward()。第一种方法如下所示:

void setup()
{
    frontServo.attach(2);
    rearServo.attach(3);

    moveForward(5);
}

void loop()
{
}

第二个看起来像这样:

void setup()
{
    frontServo.attach(2);
    rearServo.attach(3);
}

void loop()
{
    moveForward(5);
    exit(0);
}
于 2012-12-19T22:59:59.530 回答
0

Since you probably will want to eventually do more than move the robot just 5 steps, I'd suggest using a variable flag to hold the robot state. It only executes the movement routine when the flag has been set to true.

If you are using serial, when a move command is received (and the number of steps, direction perhaps?) you set the flag to true and then issue the move command. If you are using sensors or buttons, the same logic applies.

You will need some logic to handle an incoming movement command while a movement is occurring (though with your tight movement loop you actually won't be able to respond to incoming commands unless you use interrupts - but you want to consider this sort of thing if you are planning to build out a full movement bit of firmware).

boolean shouldMove;

void setup()
{
 shouldMove = true;//set the flag
}

void loop()
{
  if (shouldMove){
    moveForward(5);
  }
}


void moveForward(int steps)
{
 shouldMove = false; //clear the flag
  for (int x = steps; steps > 0; steps--) {
   // tight loop controlling movement
  }
}

}

于 2012-12-20T02:00:16.030 回答