Robot courier Lesson 2.2 All coursesFor teachersStudy in the app Student Arduino Uno + L298P motor shield
Topic 2 · Lesson 2.2

Turns and reversals

The robot turns 90° in place and turns 180°. You choose the turning time yourself.

2 × 45 min1–2 students per robotPractice

Lesson result

The robot turns 90° left and right and turns 180°. The timing of turns is selected and recorded in the logbook, turns are designed with functions.

You will learn

  • Explain why the robot spins in place when the wheels rotate in different directions.
  • Select the turning time by experiment and check it by repeating it.
  • Write the functions turnLeft(), turnRight() and turnAround().
  • Predict where the robot will arrive based on the sequence of movements.

Need to know

  • 2.1 Motors: driving and stopping

Will need

Geared motor × 2Motor shield L298P (Amp)Motor battery compartment with switch

Why this lesson

The robot can drive forward and backward. But on the field of the final task you need to turn towards the loads and turn around. Today the robot will learn to turn on the spot, and you will learn to select numbers with experience, like a real engineer.

Warm up · remember
  1. Which command sets the direction of rotation of the wheel?
  2. What happens if you turn on the motors and don’t write stopMotors()?
  3. How does a function description differ from its call?
1
Lesson 1 · 45 min
Rotate in place
1

Wheels in different directions

10 min

What should a robot do. The courier needs to change direction: turn towards the branch and turn around for the return trip. We get the turn using the same two motors, without a separate steering mechanism.

What we use and how it works. When the wheels travel different distances, the body turns. If one wheel rotates forward and the other rotates backward, the robot turns approximately around the middle between the wheels. The turning function combines wheel directions, rotation time and stopping.

How to link a dimension to an action. In this lesson we set the angle by the operating time of the motors. This is an approximation: battery charge, coverage and slippage change the result. Let's measure the resulting angle, select the time and repeat the experiment. The name turnLeft by itself does not guarantee 90 degrees - this must be confirmed by testing.

Predict

The left wheel spins backward, the right wheel spins forward at the same speed. What will the robot do? Show with your hands.

  1. Type a sketch L22_Turn_Test and load it with the motors power off.
Turning testL22_Turn_Test.ino.ino
const int LEFT_DIR_PIN = 7;const int LEFT_SPEED_PIN = 6;const int RIGHT_DIR_PIN = 4;const int RIGHT_SPEED_PIN = 5;const int FORWARD = HIGH;const int BACKWARD = (FORWARD == HIGH) ? LOW : HIGH; int turnSpeed = 100;int turnMs = 400; // подбираем: время поворота на 90° void drive(int leftDir, int leftSpeed, int rightDir, int rightSpeed) {  digitalWrite(LEFT_DIR_PIN, leftDir);  digitalWrite(RIGHT_DIR_PIN, rightDir);  analogWrite(LEFT_SPEED_PIN, leftSpeed);  analogWrite(RIGHT_SPEED_PIN, rightSpeed);} void stopMotors() {  analogWrite(LEFT_SPEED_PIN, 0);  analogWrite(RIGHT_SPEED_PIN, 0);} void setupMotors() {  pinMode(LEFT_DIR_PIN, OUTPUT);  pinMode(LEFT_SPEED_PIN, OUTPUT);  pinMode(RIGHT_DIR_PIN, OUTPUT);  pinMode(RIGHT_SPEED_PIN, OUTPUT);  stopMotors();} void setup() {  setupMotors();  delay(2000);   // Левое колесо назад, правое вперёд: робот крутится на месте налево.  drive(BACKWARD, turnSpeed, FORWARD, turnSpeed);  delay(turnMs);  stopMotors();} void loop() {}
  1. Place the robot on the floor, on a piece of paper. Draw a line along his nose with a pencil.
  2. Turn on the power to the motors and press Reset.
It should work

The robot spins in place to the left and stops. The nose turned, but most likely not exactly 90°.

How it works: Why the robot spins in place

The wheels push the robot in different directions with the same force. It doesn’t go forward and backward—it rotates around a point in the middle between the wheels. The longer the motors are turned on, the greater the rotation angle.

Predict

The robot must turn left on the spot. Which wheel should spin forward and which should spin backward? Record before launch.

  1. Create a sketch L22_Turn_Test according to the template. Functions drive and stopMotors from lesson 2.1 is already there. Write the turn in setup() according to his forecast.
Template: rotation testL22_Turn_Test_Gaps.ino.ino
// Шаблон среднего уровня. Напиши код в разделе «Твоя часть» по целям в комментариях. const int LEFT_DIR_PIN = 7;const int LEFT_SPEED_PIN = 6;const int RIGHT_DIR_PIN = 4;const int RIGHT_SPEED_PIN = 5;const int FORWARD = HIGH;const int BACKWARD = (FORWARD == HIGH) ? LOW : HIGH;int turnSpeed = 100;int turnMs = 400; // подбираем: время поворота на 90° // ===== Твоя часть: напиши сам ===== void setup() {  setupMotors();  delay(2000);   // Робот крутится на месте налево turnMs миллисекунд и останавливается.} // ===== Готовое из урока 2.1 — не меняй ===== void drive(int leftDir, int leftSpeed, int rightDir, int rightSpeed) {  digitalWrite(LEFT_DIR_PIN, leftDir);  digitalWrite(RIGHT_DIR_PIN, rightDir);  analogWrite(LEFT_SPEED_PIN, leftSpeed);  analogWrite(RIGHT_SPEED_PIN, rightSpeed);} void stopMotors() {  analogWrite(LEFT_SPEED_PIN, 0);  analogWrite(RIGHT_SPEED_PIN, 0);} void setupMotors() {  pinMode(LEFT_DIR_PIN, OUTPUT);  pinMode(LEFT_SPEED_PIN, OUTPUT);  pinMode(RIGHT_DIR_PIN, OUTPUT);  pinMode(RIGHT_SPEED_PIN, OUTPUT);  stopMotors();} void loop() {}
  1. Place the robot on the floor, on a piece of paper. Draw a line along his nose with a pencil. Turn on the power to the motors and press Reset.
  2. Change the program so that the robot turns to the right. Check it out.
Hint: The robot is moving, not spinning

If both wheels turn in the same direction, the robot moves. To turn in place, different directions are needed.

It should work

The robot spins in place to the left, and after your change - to the right. The forecast has been verified.

Requirement. In my program L21_Moves from lesson 2.1 do a turning test: the wheels spin in different directions at the same speed turnSpeed for turnMs, then the robot stops. Save as L22_Turn_Test.

Research: what the robot revolves around.

  1. Place the robot on a piece of paper and trace both wheels with a pencil.
  2. Start the turn and circle the wheels again. Find the point around which the robot turned.
  3. Does it line up with the center between the wheels? If not, how many centimeters and why?
Hint: How to find the turning point

Connect the old and new positions of each wheel. The turning point lies where these positions are equally distant.

It should work

The rotation test works. The logbook contains a drawing, a turning point and an explanation of why it is there.

2

Select the time to turn 90°

20 min

A 90° turn takes some time in milliseconds. You can only know it through experience.

  1. Draw two lines on a sheet of paper at right angles (a square or the edge of a notebook).
  2. Place the robot with its nose along the first line. Launch the program.
  3. If the robot doesn’t turn it right, increase turnMs, if turned upside down, reduce it. Change it little by little: 20–50 ms.
  4. When the turn is successful, repeat it three times. Record the time in a journal.
AttemptturnMsWhat happened
1400
2
3
It should work

The robot turns approximately 90° three times in a row. The time is recorded in the journal.

Hint: Turns differently every time

Check that the battery is charged: when the battery is discharged, the motors spin slower. The floor must be smooth and non-slippery. A slight difference between attempts is normal.

A 90° turn takes some time in milliseconds. You can only know it through experience. How to choose - decide for yourself, but change only turnMs and write down each attempt.

  1. Draw two lines at right angles on the sheet. Place the robot with its nose along the first one.
  2. Pick up turnMs, until the robot turns 90°. The log contains at least four attempts and an explanation of why you chose the next number.
  3. When the turn is successful, repeat it three times.
AttemptturnMsWhat happenedWhat to change next and why
1
2
3
4
Hint: What number to start with

Look how much the robot turned in the test with turnMs = 400. More than 90° or less?

Hint: Turns differently every time

Make sure the battery is charged and the floor is level and not slippery. A slight difference between attempts is normal.

It should work

The robot turns approximately 90° three times in a row. The log contains four attempts with an explanation and the final time.

Select the turning time method and find out how much you can trust him.

  1. Find one time at which the robot clearly does not turn enough, and one at which it clearly turns over. Try the middle between them and narrow the gap until the error is less than 5°.
  2. With the time you find, make five turns in a row. For each, mark on a piece of paper where the nose is pointing and use a protractor to measure the error in degrees.
  3. Repeat step 2 for another turnSpeed (for example, 160). At what speed are turns more accurate and consistent?
  4. Will the robot turn right in the same time? Check and write down.
turnSpeedturnMsErrors 5 turns, °Biggest mistake, °
100
160
Tip: How to measure error without a protractor

Compare the nose mark with the 90° line at a distance of 10 cm from the center of rotation: 1 cm to the side is approximately 6°.

It should work

In the log - the search method, time for two speeds, errors of five turns and the conclusion: which turnSpeed take and whether the time is the same on the left and right.

3

Rotate 180°

15 min
Predict

If at 90° you need, for example, 400 ms, how much is needed at 180°? Write down your prediction.

  1. Put in turnMs your time multiplied by 2. Check the reversal.
  2. Adjust the number if necessary. Record the turnaround time in your journal.
It should work

The robot turns around and looks in the opposite direction. The turning time is recorded.

How it works: Why exactly twice does not always work out

At the beginning of the turn, the motors take time to accelerate, and at the end the robot slips a little due to inertia. Therefore, the time for a 180° may be slightly less than two 90° turns. Experience is more important than calculation.

Predict

How many milliseconds does it take to turn 180° if you know your time to turn 90°? Write down your forecast.

  1. Check the forecast on the floor and adjust the number if necessary. Record the turnaround time.
  2. Answer in the journal: did it turn out to be exactly twice as much as 90°? If not, how do you explain it?
Hint: Why not exactly double

Think about what happens at the beginning of a turn, when the wheels are just starting to move, and at the end, when the motors are already turned off.

It should work

The robot turns around and looks in the opposite direction. The turnaround time and explanation are recorded.

  1. Predict the time of the 90° turn using your time and check on the floor. Find the exact time using the same method as for 90°.
  2. Compare: how many times is the time of 180° longer than the time of 90°? Explain in the journal where the difference comes from. Give two reasons.
  3. Derive a rule: how many milliseconds does it take per degree for a turn and for a 90° turn? Which number is more accurate for a 45° rotation? Check it out.
It should work

The reversal time has been selected. The logbook contains a comparison with a double 90° rotation, two reasons for the difference, and a test of the 45° rule.

2
Lesson 2 · 45 min
Rotation functions
4

Rotation functions

12 min
  1. Create a sketch L22_Turns. Write your times from the journal into turn90Ms and turn180Ms.
Rotation functionsL22_Turns.ino.ino
const int LEFT_DIR_PIN = 7;const int LEFT_SPEED_PIN = 6;const int RIGHT_DIR_PIN = 4;const int RIGHT_SPEED_PIN = 5;const int FORWARD = HIGH;const int BACKWARD = (FORWARD == HIGH) ? LOW : HIGH; int speed = 100;int turnSpeed = 100;int turn90Ms = 400;  // впиши своё время из журналаint turn180Ms = 800; // впиши своё время из журнала void drive(int leftDir, int leftSpeed, int rightDir, int rightSpeed) {  digitalWrite(LEFT_DIR_PIN, leftDir);  digitalWrite(RIGHT_DIR_PIN, rightDir);  analogWrite(LEFT_SPEED_PIN, leftSpeed);  analogWrite(RIGHT_SPEED_PIN, rightSpeed);} void stopMotors() {  analogWrite(LEFT_SPEED_PIN, 0);  analogWrite(RIGHT_SPEED_PIN, 0);} void setupMotors() {  pinMode(LEFT_DIR_PIN, OUTPUT);  pinMode(LEFT_SPEED_PIN, OUTPUT);  pinMode(RIGHT_DIR_PIN, OUTPUT);  pinMode(RIGHT_SPEED_PIN, OUTPUT);  stopMotors();} void forward(int ms) {  drive(FORWARD, speed, FORWARD, speed);  delay(ms);  stopMotors();} void turnLeft() {  drive(BACKWARD, turnSpeed, FORWARD, turnSpeed);  delay(turn90Ms);  stopMotors();} void turnRight() {  drive(FORWARD, turnSpeed, BACKWARD, turnSpeed);  delay(turn90Ms);  stopMotors();} void turnAround() {  drive(BACKWARD, turnSpeed, FORWARD, turnSpeed);  delay(turn180Ms);  stopMotors();} void setup() {  setupMotors();  delay(2000);   for (int i = 0; i < 4; i++) {    forward(1000);    delay(300);    turnLeft();    delay(300);  }} void loop() {}
  1. Find the difference between turnLeft() and turnRight(). What has changed?
It should work

The program is checked without errors. Can you explain how the rotation functions differ?

  1. Create a sketch L22_Turns according to the template. Write your times from the journal into turn90Ms and turn180Ms.
  2. Write turnLeft, turnRight, turnAround and square in setup() himself. Function forward from lesson 2.1 is already there - use it as a sample.
Template: rotation functionsL22_Turns_Gaps.ino.ino
// Шаблон среднего уровня. Напиши код в разделе «Твоя часть» по целям в комментариях. const int LEFT_DIR_PIN = 7;const int LEFT_SPEED_PIN = 6;const int RIGHT_DIR_PIN = 4;const int RIGHT_SPEED_PIN = 5;const int FORWARD = HIGH;const int BACKWARD = (FORWARD == HIGH) ? LOW : HIGH;int speed = 100;int turnSpeed = 100;int turn90Ms = 400;  // впиши своё время из журналаint turn180Ms = 800; // впиши своё время из журнала // ===== Твоя часть: напиши сам ===== void turnLeft() {  // Поворот на месте налево на 90° по времени turn90Ms; в конце колёса стоят.} void turnRight() {  // Поворот на месте направо на 90° по времени turn90Ms; в конце колёса стоят.} void turnAround() {  // Разворот на месте на 180° по времени turn180Ms; в конце колёса стоят.} void setup() {  setupMotors();  delay(2000);   // Квадрат: четыре раза — вперёд 1 секунду, пауза, поворот налево, пауза.} // ===== Готовое из урока 2.1 — не меняй ===== void drive(int leftDir, int leftSpeed, int rightDir, int rightSpeed) {  digitalWrite(LEFT_DIR_PIN, leftDir);  digitalWrite(RIGHT_DIR_PIN, rightDir);  analogWrite(LEFT_SPEED_PIN, leftSpeed);  analogWrite(RIGHT_SPEED_PIN, rightSpeed);} void stopMotors() {  analogWrite(LEFT_SPEED_PIN, 0);  analogWrite(RIGHT_SPEED_PIN, 0);} void setupMotors() {  pinMode(LEFT_DIR_PIN, OUTPUT);  pinMode(LEFT_SPEED_PIN, OUTPUT);  pinMode(RIGHT_DIR_PIN, OUTPUT);  pinMode(RIGHT_SPEED_PIN, OUTPUT);  stopMotors();} void forward(int ms) {  drive(FORWARD, speed, FORWARD, speed);  delay(ms);  stopMotors();} void loop() {}
  1. Click Check.
Hint: How are turns different?

Compare your turning test: which wheels turn to the left and in which direction, and which wheels turn to the right? What about when turning?

Hint: Four times

A cycle helps to repeat the same thing four times for from lesson 1.1.

It should work

The program is checked without errors. Can you explain how the rotation functions differ?

Requirement. Continue with your program L21_Moves from lesson 2.1 and save as L22_Turns:

  • turnLeft(), turnRight(), turnAround() - 90° turns and a turn according to your times, each ending with a stop;
  • times are named variables at the beginning of the sketch; if in the selection step the time to the left and to the right turns out to be different, each turn has its own variable;
  • sets the direction and speed of the wheels only drive;
  • in setup() - square for the next step: four times “forward 1 second, left.”
Hint: Idea (1 of 2)

Rotation is drive with wheels in different directions, waiting and stopping.

Hint: Code snippet (2 of 2)

drive(BACKWARD, turnSpeed, FORWARD, turnSpeed); - this is how the robot spins to the left. What should I change to turn right?

It should work

The program fulfills the requirement and checks without errors.

5

Square

18 min
Predict

The program repeats 4 times: “forward 1 second, to the left.” Where will the robot end up and where will it look? Draw the path in a journal.

  1. Mark the start with tape. Run the program on the floor.
  2. Compare where the robot stopped with the forecast.
  3. How far is the robot from reaching the start line? Write it down.
It should work

The robot passes the square and returns close to the start, with its nose in the same direction.

Find the mistake · The square turned into a line

The neighbors' robot moves forward, spins, but it doesn't turn out square: it goes back and forth. In their turnLeft() worth delay(turn180Ms). What's wrong?

Predict

The program repeats 4 times: “forward 1 second, left.” Draw the path in a journal. Where will the robot end up and where will it look?

  1. Mark the start with tape. Run the program on the floor three times.
  2. Each time, measure how many centimeters the robot missed the start, and approximately how many degrees its nose is turned.
  3. Explain in the journal why the error at the end is greater than the error of one turn.
It should work

Three runs with measurements and an explanation for the accumulation of errors.

Find the mistake · The square turned into a line

The neighbors' robot moves forward, spins, but it doesn't turn out square: it goes back and forth. In their turnLeft() worth delay(turn180Ms). What's wrong?

  1. Run the square three times. Each time, measure how far the robot missed the start (in centimeters) and how much the nose is turned (in degrees).
  2. Estimate the error of one turn: divide the error of direction at the end by four. Does it match the error you measured when selecting the time?
  3. What spoils the square more: a turning error or a slip on a straight line? How can this be verified by separate experiment? Run it and record the conclusion.
Find the mistake · The square turned into a line

The neighbors' robot moves forward, spins, but it doesn't turn out square: it goes back and forth. In their turnLeft() worth delay(turn180Ms). What's wrong?

It should work

Measurements of three squares, assessment of the error of one turn and experience that showed the main reason for the mistake.

6

Quests by level

15 min
Basic · Rotate and rotate

The robot turns left and right by 90° and turns 180° according to your times.

Medium level · Reversal back to line

Place a strip of duct tape on the floor. Place the robot on it, make a 180° turn. The robot should again stand along the strip, and the nose should move away from it no further than its width. This is how the reversal will work in the final task.

Advanced · Rotate to any angle

Write the function turn(int degrees): positive angle - to the left, negative - to the right. Count time as degrees × msPerDegree, where msPerDegree = turn90Ms / 90. Check at 45°, 90° and 180°. Where is accuracy worst and why?

Test yourself

Test yourself

Select answers to prepare. They are not stored or evaluated on the site. Take the knowledge test in the course syllabus or discuss the answers with your instructor.

● Basic

1.The left wheel spins forward, the right wheel spins backward at the same speed. What does the robot do?
2.The robot does not rotate to 90°. What to change?
3.Why is the turning time selected by experience, and not taken from a textbook?
4.Program: “forward, left” 4 times. Where will the robot end up?
5.The battery is low. What is most likely to happen with time rotations?

★ Intermediate level

1.A 180° turn lasts 900 ms, but the robot under-turns a little. What to do?
2.Why check the spread on a strip of duct tape?
3.When turnMs = 400, the robot turned 70°. What number should you try next?
4.Why can't a 180° turn take exactly twice as long as a 90° turn?
5.How is turnRight() different from turnLeft()?

★★ Advanced level

1.turn90Ms = 600. How many milliseconds will turn(45) take if msPerDegree = turn90Ms / 90?
2.How does the turn(int degrees) function know which way to turn?
3.Errors of five turns: with turnSpeed = 100 - +4°, −6°, +5°, −3°, +2°; at 160 - +1°, −2°, +2°, 0°, −1°. Which speed should I choose?
4.At 300 ms the robot clearly does not turn enough, at 500 ms it clearly over turns. What to try next?
5.turn90Ms = 400. For 45°, the coefficient from 90° was 200 ms, and the robot turned only 35°. Why?

Answer questions at your level. Correct answers needed: Beginner - 4 out of 5; Average - 4 out of 5; Advanced - 4 out of 5. Answers will be checked by the teacher or course program.

Summary

The robot turns according to the time that you selected through experience. This is a simple method, but it depends on the battery and floor surface. In lesson 4.2, the robot will learn to turn more accurately - using sensors: spin until it finds a new line.

How to confirm the result

For each experiment, save the conditions, program version, observation and conclusion. When comparing attempts, change one reason at a time; unsuccessful attempts also remain in the log. Marking a result refers to actions that have already been completed; there is no need to repeat them for the sake of marking. If the result is not obtained, write down the discrepancy and the next hypothesis to be tested. A model, measurements of a real robot, and an explanation are different types of evidence.

Lesson vocabulary

turn on the spotThe wheels spin in different directions, and the robot rotates around the middle between the wheels.
calibrationSelecting a number based on experience: for example, how many milliseconds it takes to turn 90°.
errorHow different the result is from the desired one: for example, the robot turned 85° instead of 90°.