Turns and reversals
The robot turns 90° in place and turns 180°. You choose the turning time yourself.
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
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.
- Which command sets the direction of rotation of the wheel?
- What happens if you turn on the motors and don’t write
stopMotors()? - How does a function description differ from its call?
Wheels in different directions
10 minWhat 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.
The left wheel spins backward, the right wheel spins forward at the same speed. What will the robot do? Show with your hands.
- Type a sketch
L22_Turn_Testand load it with the motors power off.
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() {}
- 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.
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.
The robot must turn left on the spot. Which wheel should spin forward and which should spin backward? Record before launch.
- Create a sketch
L22_Turn_Testaccording to the template. FunctionsdriveandstopMotorsfrom lesson 2.1 is already there. Write the turn insetup()according to his forecast.
// Шаблон среднего уровня. Напиши код в разделе «Твоя часть» по целям в комментариях. 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() {}
- 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.
- 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.
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.
- Place the robot on a piece of paper and trace both wheels with a pencil.
- Start the turn and circle the wheels again. Find the point around which the robot turned.
- 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.
The rotation test works. The logbook contains a drawing, a turning point and an explanation of why it is there.
Select the time to turn 90°
20 minA 90° turn takes some time in milliseconds. You can only know it through experience.
- Draw two lines on a sheet of paper at right angles (a square or the edge of a notebook).
- Place the robot with its nose along the first line. Launch the program.
- If the robot doesn’t turn it right, increase
turnMs, if turned upside down, reduce it. Change it little by little: 20–50 ms. - When the turn is successful, repeat it three times. Record the time in a journal.
| Attempt | turnMs | What happened |
|---|---|---|
| 1 | 400 | |
| 2 | ||
| 3 |
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.
- Draw two lines at right angles on the sheet. Place the robot with its nose along the first one.
- 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. - When the turn is successful, repeat it three times.
| Attempt | turnMs | What happened | What 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.
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.
- 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°.
- 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.
- Repeat step 2 for another
turnSpeed(for example, 160). At what speed are turns more accurate and consistent? - Will the robot turn right in the same time? Check and write down.
turnSpeed | turnMs | Errors 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°.
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.
Rotate 180°
15 minIf at 90° you need, for example, 400 ms, how much is needed at 180°? Write down your prediction.
- Put in
turnMsyour time multiplied by 2. Check the reversal. - Adjust the number if necessary. Record the turnaround time in your journal.
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.
How many milliseconds does it take to turn 180° if you know your time to turn 90°? Write down your forecast.
- Check the forecast on the floor and adjust the number if necessary. Record the turnaround time.
- 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.
The robot turns around and looks in the opposite direction. The turnaround time and explanation are recorded.
- 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°.
- 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.
- 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.
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.
Rotation functions
12 min- Create a sketch
L22_Turns. Write your times from the journal intoturn90Msandturn180Ms.
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() {}
- Find the difference between
turnLeft()andturnRight(). What has changed?
The program is checked without errors. Can you explain how the rotation functions differ?
- Create a sketch
L22_Turnsaccording to the template. Write your times from the journal intoturn90Msandturn180Ms. - Write
turnLeft,turnRight,turnAroundand square insetup()himself. Functionforwardfrom lesson 2.1 is already there - use it as a sample.
// Шаблон среднего уровня. Напиши код в разделе «Твоя часть» по целям в комментариях. 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() {}
- 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.
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?
The program fulfills the requirement and checks without errors.
Square
18 minThe 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.
- Mark the start with tape. Run the program on the floor.
- Compare where the robot stopped with the forecast.
- How far is the robot from reaching the start line? Write it down.
The robot passes the square and returns close to the start, with its nose in the same direction.
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?
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?
- Mark the start with tape. Run the program on the floor three times.
- Each time, measure how many centimeters the robot missed the start, and approximately how many degrees its nose is turned.
- Explain in the journal why the error at the end is greater than the error of one turn.
Three runs with measurements and an explanation for the accumulation of errors.
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?
- 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).
- 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?
- 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.
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?
Measurements of three squares, assessment of the error of one turn and experience that showed the main reason for the mistake.
Quests by level
15 minThe robot turns left and right by 90° and turns 180° according to your times.
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.
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
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
★ Intermediate level
★★ Advanced level
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 spot | The wheels spin in different directions, and the robot rotates around the middle between the wheels. |
| calibration | Selecting a number based on experience: for example, how many milliseconds it takes to turn 90°. |
| error | How different the result is from the desired one: for example, the robot turned 85° instead of 90°. |