VEX V5 - Driving Challenge with Functions and Loops
Challenge: Drive a Square
The challenge is to make the robot drive in a square pattern. Go forward, turn right, Go forward....The square course is set up using 4 cones to indicate the corners of the square. The robot must travel outside of the cones and complete one trip around the square.
Code
You could take the previous lesson and just copy and paste over and over, but it is much more efficient to use variables, functions and loops.
Code below implements a drive function, then calls it 9 times to make the square and finally stop the motors. This is just a template, THIS IS NOT THE SOLUTION!!!
first two lines are just the devices you need to be able to do this challenge which you will declare in your device list.
motor RM = motor(PORT1,true) "true" means this motor is reversed motor LM = motor(PORT2,false) void drive(int lspeed, int rspeed, int wt) { RM.spin(forward,lspeed,pct); LM.spin(forward,rspeed,pct); wait(wt); } int main() { wait(500, msec); drive(50,50,500); drive(50,-50,500); drive(50,50,500); drive(50,-50,500); drive(50,50,500); drive(50,-50,500); drive(50,50,500); drive(50,-50,500); drive(0,0,0); }
Although this code is still pretty long we have reduced the number of lines by about 1/3. Each time we write drive(50,50,500); we are replacing 3 lines of code.
While Loop
There is still a lot of repetition that could be reduced further using loops.
brain Brain; motor RM = motor(PORT1,true); motor LM = motor(PORT2,false); void drive(int lspeed, int rspeed, int wt) { RM.spin(forward,lspeed,pct); LM.spin(forward,rspeed,pct); wait(wt); } int main() { int x=1; wait(500, msec); while(x<=4) { drive(50,50,500); drive(50,-50,500); x++; } drive(0,0,0); }
For Loop
An even more simplified version uses a for loop in main.
int main() { wait(500,msec); for(int x=1;x<=4;x++) { drive(50,50,500); drive(50,-50,500); } drive(0,0,0); }