Line Robot - Basic lessons - Exercises - Variable speed
Task: change robot's speed.
Slowly increase robot's speed from 0 to 127, then decrease from 127 to 0, and stop the program.
Solution
void RobotLine::loop() {
static int speed = 0;
static int step = 1;
go(speed , speed );
speed += step;
if (speed == -1)
end();
else if (speed == 127)
step = -1;
delayMs(50);
}
- We declare 2 static variables ("speed" and "step"), so that their values will be available during different runs of the function.
-
speed is current speed, step will change the speed.
- The motors are started using the current speed.
- Speed is altered according to the "step".
- If the current speed is 0, and we add -1 (so, the motors were slowing down), speed will be -1 now, and the program must end.
- If the current speed is 127, we reached top speed, and must start slowing down. To do that, we change the step.
- Some delay is needed. Otherwise the program will end too soon, not giving the motors enough time to start rotating. Adjust the delay.