The next step is to make our robot move forward and then backward.
To move forward we will send a "move forward" signal to both the right and left motors.
We will then delay for two seconds. After that we will stop for one second and
move backward for two seconds. We can repeat this in our loop.
1234567
intright_forward=5;intright_reverse=3;intleft_forward=6;intleft_reverse=9;intforward_time=2000;// how long should we move forward?intstop_time=1000;// how long should we stop between directions?intreverse_time=2000;// how long should we go backward?
Here is our setup code:
1 2 3 4 5 6 7 8 9101112131415
voidsetup(){// Turn these pins on for PWM OUTPUTpinMode(right_forward,OUTPUT);pinMode(right_reverse,OUTPUT);pinMode(left_forward,OUTPUT);pinMode(left_reverse,OUTPUT);// turn all the motors offdigitalWrite(right_forward,LOW);digitalWrite(right_reverse,LOW);digitalWrite(left_forward,LOW);digitalWrite(left_reverse,LOW);// for debugging. The output will appear on the serial monitor// To open the serial monitor, click the magnafing glass icon in the upper right cornerSerial.begin(9600);// open the serial port at 9600 bps}
We can also create a set of functions for each of our drive commands. Functions
not only makes it easy to reuse code, but they also make our programs easier
for us to read.
Here are two C functions for going turning right and moving forward. These
two functions are all we will need to create a simple collision avoidance robot.
Here are four C functions for going forward, reverse and turning right and left.
Note that the turning functions (turn right and turn left) both have
a function parameter. This is the length of time that the robots
will be turning. The longer the delay, the larger an angle the
robot will turn.
// turn right for turn_delay_time msvoidturn_right(intturn_delay_time){Serial.println("turning right");analogWrite(RIGHT_FORWARD_PIN,0);analogWrite(RIGHT_REVERSE_PIN,power_turn_level);analogWrite(LEFT_FORWARD_PIN,power_turn_level);analogWrite(LEFT_REVERSE_PIN,0);delay(turn_delay_time);}voidturn_left(intturn_delay_time){Serial.println("turning left");analogWrite(RIGHT_REVERSE_PIN,0);analogWrite(RIGHT_FORWARD_PIN,power_turn_level);analogWrite(LEFT_REVERSE_PIN,power_turn_level);analogWrite(LEFT_FORWARD_PIN,0);delay(turn_delay_time);}voidmove_forward(){Serial.println("moving forward");analogWrite(RIGHT_FORWARD_PIN,power_forward_right);analogWrite(RIGHT_REVERSE_PIN,0);analogWrite(LEFT_FORWARD_PIN,power_forward_left);analogWrite(LEFT_REVERSE_PIN,0);}voidmove_reverse(){Serial.println("moving reverse");analogWrite(RIGHT_FORWARD_PIN,0);analogWrite(RIGHT_REVERSE_PIN,power_forward_right);analogWrite(LEFT_FORWARD_PIN,0);analogWrite(LEFT_REVERSE_PIN,power_forward_left);}