Lesson: Exercise: Drive in a Square Pattern

Learn how to drive the EV3 robot in a square pattern by programming only two moves.

Understand how to drive the EV3 robot is a square pattern. This involves turning and making 8 moves (4 straight and 4 turns) by programming only 2.


Now lets try something more difficult. Lets write a program to drive your robot in a square pattern. This requires 8 moves: drive straight for some amount of time, turn, drive straight, turn, drive straight, turn, drive strait, turn. Lets use the Java for loop to program only 2 moves, drive straight and turn but then repeat those two moves to get the total driving moves we need.

Create a new package called ev3.exercises.driveSquare. Create a Java class called DriveSquare then copy and paste the code below into that class:

In this exercise we use the for loop to execute the two moves 4 times to drive the robot in a square.

Note that the two driving "moves" which we defined as "drive straight" and "turn", consist of starting the motors, waiting some amount of time then stopping the motors.

Note that we said turn right so we reversed motorA to make the turn. Which motor you reverse depends on how you wired your robot and which end you consider the "front". You will need to make some adjustments to the code to make the robot move correctly for your design.

Also note that the time to run the motors when making the turn may need to be adjusted to get good 90 degree turns. We reverse one motor and drive the other motor forward to make the robot turn in place or pivot to make a nice square. Later you will learn how to make accurate turns uding a gyro or the Regulated Motor's tachometer feature. 

Can you modify the code to make the turns rounded?

Finally, when the square is done, the robot turns one more time to it's original heading. This is because we execute the turn 4 times when you really only need 3 turns to complete the square. Can you modify the code to not make the extra turn?

One last thing. When you put this code into Eclipse, an error indication will appear on the for statement. Can you figure out what is wrong and fix it? Review the lesson on the for statement if needed.


Lesson navigation: