Motors: driving and stopping
The first movements of the robot: forward, backward and the obligatory stop from the program.
Lesson result
The robot drives forward, stops and returns back according to the program. The movements are formalized by the functions forward(), backward() and stopMotors().
You will learn
- Explain what the direction contact sets and what the speed contact sets.
- Turn on and stop motors using the digitalWrite and analogWrite commands.
- Write motion functions and call them in order.
- Explain why movement does not end without a stop command.
Need to know
- 1.1 Assembling the robot and reviving the board
Will need
Why this lesson
The robot is assembled, but is still standing. He will go today. You will learn how the board commands the motors, and teach the robot to go forward, backward and - most importantly - stop according to the program.
- How many times is executed
setup(), and how much -loop()? - What does
digitalWrite(вывод, HIGH)? - Where is the left motor on your robot?
We check the motors on the stand: the wheels do not touch the table. We load the program with the motors power off. To stop the experiment, turn off the power to the motors with the switch.
Prepare the robot
5 minWhat should a robot do. The robot needs to start moving, drive through the area and stop. To do this, we will learn to separately set the direction and power of each of the two motors, and then combine the commands into understandable actions.
What we use and how it works. The motors are connected via the L298P driver: the Arduino pin supplies the control signal, and current flows to the motor through the driver. DIR selects the direction. PWM quickly alternates between turning the power on and off; A larger analogWrite value means a larger proportion of time on. This is a power command, not a measured speed in centimeters per second.
How to link a dimension to an action. If both wheels turn forward, the robot moves; if one is weaker, it is rejected. delay only delays the next command: the motor continues to execute the previous one. Therefore, the program needs a separate stop. First we observe the wheels on the stand, then we check the direction, distance and stop on the field.
- Place the robot on the stand so that both wheels are hanging in the air.
- Find the motor power switch and turn it off.
- Connect the USB cable.
The wheels are hanging, the power to the motors is turned off, the board is connected to the computer.
Turn on the left motor
15 minEach motor is controlled by two contacts. Contact directions decides which way the wheel turns. Contact speed decides how strong: a number from 0 (worth it) to 255 (full power). The left motor is connected to the contacts 7 (direction) and 6 (speed).
const int LEFT_DIR_PIN = 7;const int LEFT_SPEED_PIN = 6;const int FORWARD = HIGH; void setup() { pinMode(LEFT_DIR_PIN, OUTPUT); pinMode(LEFT_SPEED_PIN, OUTPUT); digitalWrite(LEFT_DIR_PIN, FORWARD); analogWrite(LEFT_SPEED_PIN, 100); delay(2000); analogWrite(LEFT_SPEED_PIN, 0);} void loop() {}
What will the wheel do after loading? How many seconds will it spin? Will it stop on its own? Tell your partner before launch.
- Type the program and load it with the power to the motors turned off.
- Turn on the power to the motors and press the Reset button on the board: the program will start again.
- Compare what happened with your prediction.
The left wheel spins forward for 2 seconds and stops.
How it works: What each line means
const int LEFT_DIR_PIN = …;– name for the contact number. Then in the program we write the name, not the number: it’s clearer and there are fewer errors.digitalWrite(LEFT_DIR_PIN, FORWARD);— select the “forward” direction.analogWrite(LEFT_SPEED_PIN, 100);- turn on the motor with a power of 100 out of 255.analogWrite(LEFT_SPEED_PIN, 0);- stop the motor.- Everything is written in
setup(), so it is executed once.loop()empty: after stopping, the robot just stands there.
| What do you see | What to do |
|---|---|
| The wheel doesn't spin | Is the power to the motors turned on? Press Reset after turning it on. |
| The wheel turns backwards | Write this down in the journal - we'll correct the direction in the next step. |
| The right wheel is spinning | The motor wires are mixed up on the shield. Turn off the power and swap the wires in terminals M1 and M2. |
Each motor is controlled by two contacts. Contact directions decides which way the wheel turns. Contact speed decides how strong: a number from 0 (worth it) to 255 (full power). The left motor is connected to the contacts 7 (direction) and 6 (speed).
| Command | What does |
|---|---|
pinMode(контакт, OUTPUT); | Allows the board to control the contact |
digitalWrite(контакт, FORWARD); | Selects the forward direction |
analogWrite(контакт, сила); | Turns on the motor with a power from 0 to 255; 0 - stop |
delay(мс); | Waits the specified number of milliseconds |
- Create a sketch
L21_Left_Motoraccording to the template and writesetup()himself: what should happen is said in the comments.
// Шаблон среднего уровня. Напиши код в разделе «Твоя часть» по целям в комментариях. const int LEFT_DIR_PIN = 7;const int LEFT_SPEED_PIN = 6;const int FORWARD = HIGH; // ===== Твоя часть: напиши сам ===== void setup() { // Подготовь оба контакта левого мотора. // Левое колесо крутится вперёд 2 секунды с силой 100 из 255 и останавливается само.} void loop() {}
What happens if you forget the stop command? Write down the answer and check it only on the stand.
- Load the program with the motors power off.
- Turn on the power to the motors and press the Reset button on the board: the program will start again.
Hint: Where to start
First both contacts must become outputs, then direction, then force.
The left wheel spins forward for 2 seconds and stops. The forecast is recorded.
| What do you see | What to do |
|---|---|
| The wheel doesn't spin | Are the pins configured as outputs? Is the power to the motors turned on? Click Reset. |
| The wheel turns backwards | Write this down in the journal - we'll correct the direction in the next step. |
| The right wheel is spinning | The motor wires are mixed up on the shield. Turn off the power and swap the wires in terminals M1 and M2. |
The left motor is connected to the contacts 7 (direction) and 6 (speed). The forward direction on this set is level HIGH.
How it works: Command help
| Command | What does |
|---|---|
pinMode(pin, OUTPUT) | Allows the board to control the contact |
digitalWrite(pin, HIGH) / LOW | Motor direction |
analogWrite(pin, v) | Motor power: v from 0 (worth) to 255 |
delay(ms) | Wait ms milliseconds |
Requirement 1. Sketch L21_Left_Motor: the left wheel spins forward for exactly 2 seconds with the force from the named variable and stops itself. Pin numbers are named constants, not numbers in commands.
Acceptance.
- On the stand, the partner uses a stopwatch to time how long the wheel spins.
- Replace the direction level with the opposite one. What did the wheel do? Write down what level is on your robot - “forward”.
- Explain in the journal why the wheel stopped, although
loop()empty.
Hint: Idea (1 of 2)
Once when turned on: set up contacts, select a direction, turn on, wait, turn off.
Hint: Hint for point 3 (2 of 2)
Where the stop command was executed - in setup() or in loop()? How many times?
The wheel spins for 2 seconds and stops. The log contains the stopwatch time, the “forward” level and an explanation of the stop.
Turn on both motors
15 min- Create a sketch
L21_Both_Motorsand type the program.
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; int speed = 100; void setup() { pinMode(LEFT_DIR_PIN, OUTPUT); pinMode(LEFT_SPEED_PIN, OUTPUT); pinMode(RIGHT_DIR_PIN, OUTPUT); pinMode(RIGHT_SPEED_PIN, OUTPUT); digitalWrite(LEFT_DIR_PIN, FORWARD); digitalWrite(RIGHT_DIR_PIN, FORWARD); analogWrite(LEFT_SPEED_PIN, speed); analogWrite(RIGHT_SPEED_PIN, speed); delay(1000); analogWrite(LEFT_SPEED_PIN, 0); analogWrite(RIGHT_SPEED_PIN, 0);} void loop() {}
- Upload and test with the robot on a stand.
- Change
speedby 60, then by 200. How does the rotation change?
Both wheels turn forwards for one second and stop. With a larger speed the wheels spin faster.
How it works: Why 0–255 and not kilometers per hour
Number in analogWrite is not a speed but the proportion of time the motor is powered. At 255 it is powered continuously; at 100, about 40% of the time. Actual speed also depends on the battery and floor surface. Choose a suitable value through experiments.
The right motor is designed in the same way as the left one: direction contact 4 and speed contact 5. The names of all four contacts are already in the template.
- Create a sketch
L21_Both_Motorsaccording to the template and writesetup()himself. Use your left motor program as a model.
// Шаблон среднего уровня. Напиши код в разделе «Твоя часть» по целям в комментариях. 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;int speed = 100; // ===== Твоя часть: напиши сам ===== void setup() { // Подготовь контакты обоих моторов. // Оба колеса крутятся вперёд со скоростью speed одну секунду и останавливаются.} void loop() {}
- Upload and test with the robot on a stand.
- Change
speedby 60, then by 200. How does the rotation change?
You turn on the wheels one by one: first the left one, then the right one. Is it noticeable that they do not start at the same time? Why?
Hint: Wheels behave differently
Compare the commands for the left and right motors line by line: each requires setting, direction, force and stop.
Both wheels turn forwards for one second and stop. With a larger speed the wheels are spinning faster, the forecast is recorded.
How it works: Why 0–255 and not kilometers per hour
Number in analogWrite is not a speed but the proportion of time the motor is powered. At 255 it is powered continuously; at 100, about 40% of the time. Actual speed also depends on the battery and floor surface. Choose a suitable value through experiments.
Requirement 2. Both wheels spin forward for exactly one second at a speed from one named variable speed and stop. The right motor is connected to the contacts 4 (direction) and 5 (speed). Start with your program for the left motor and save it as L21_Both_Motors.
Research: at what date does the wheel start moving. Place on the stand speed = 20, 40, 60, 80... and write down for each wheel at what smallest number it begins to spin confidently.
speed | Is the left one spinning? | Is the right one spinning? |
|---|---|---|
| 20 | ||
| 40 | ||
| 60 |
Will these numbers be the same for two wheels? What about you and the neighboring team?
Hint: The wheel hums, but does not spin
The motor does not have enough strength to move the gearbox. This number is still a “dead zone”.
Both wheels spin for one second and stop. In the log - the lowest starting speed for each wheel and the output of what numbers speed cannot be taken.
Find the stop error
10 minNeighbors moved movement commands to loop() and removed the stop:
void loop() {
analogWrite(LEFT_SPEED_PIN, speed);
analogWrite(RIGHT_SPEED_PIN, speed);
delay(1000);
}
They waited for the robot to move for one second. What will actually happen and why? How to fix it?
Can you explain: delay is just waiting, the motors do not turn off themselves, but loop() repeats commands over and over again.
Neighbors moved traffic to loop() and added a stop:
void loop() {
analogWrite(LEFT_SPEED_PIN, speed);
analogWrite(RIGHT_SPEED_PIN, speed);
delay(1000);
analogWrite(LEFT_SPEED_PIN, 0);
analogWrite(RIGHT_SPEED_PIN, 0);
}
They waited: it drove for a second, then stopped. The wheels on the stand spin almost non-stop. Why?
- Write your answer in your journal.
- Suggest two different corrections and write them down with code: one - without
loop(), the second - leaving the movement inloop().
Hint: Second fix
Is it possible to get stuck in place after stopping so that loop() didn't happen again? Remember the defense from lesson 1.1... or the empty infinite loop while (true) { }.
Can you explain why the stop lasts a moment, and there are two corrections in the log.
At the neighbors loop() is empty, and the movement is in setup():
void forward(int ms) {
drive(FORWARD, speed, FORWARD, speed);
delay(ms);
}
void setup() {
// … настройка контактов
forward(1000);
}
void loop() {
}
The robot was supposed to drive for one second, but it keeps going until it is turned off. Why if loop() empty? Write your answer in your journal.
Requirement. Rewrite the program so that the movement remains in loop(), but the robot drove for exactly one second and did not move again. while (true) cannot be used.
- Check it on the stand: the wheels spin for one second and stay there until you press Reset.
- Explain in the log how your program “remembers” that the movement has already happened.
Hint: Idea
We need a variable that stores “already went” - bool. It is checked at the beginning loop().
The program fulfills the requirement, the explanation is recorded.
Design movements with functions
15 minWriting four lines each time is inconvenient. Let's collect them in functions: forward(), backward(), stopMotors(). Inside them are familiar commands.
- Create a sketch
L21_Movesand type the program.
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; 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 forward(int ms) { drive(FORWARD, speed, FORWARD, speed); delay(ms);} void backward(int ms) { drive(BACKWARD, speed, BACKWARD, speed); delay(ms);} void stopMotors() { analogWrite(LEFT_SPEED_PIN, 0); analogWrite(RIGHT_SPEED_PIN, 0);} void setup() { pinMode(LEFT_DIR_PIN, OUTPUT); pinMode(LEFT_SPEED_PIN, OUTPUT); pinMode(RIGHT_DIR_PIN, OUTPUT); pinMode(RIGHT_SPEED_PIN, OUTPUT); stopMotors(); delay(2000); // время убрать руки от робота forward(1000); stopMotors(); delay(500); backward(1000); stopMotors();} void loop() {}
- Find where the functions described and where are they are called. Show it to your partner.
How it works: How a function with a parameter works
void forward(int ms) - function named forward and the parameter ms. When we write forward(1000), inside a function ms is equal to 1000. So one function can drive at any time.
drive(…) is an auxiliary function: it immediately sets the direction and speed of both wheels. Other functions use it.
The program passes the build check without errors. You can show the definition and call of forward.
Writing four lines each time is inconvenient. Let's collect them in functions: forward(), backward(), stopMotors(). Functions drive and forward in the template is a sample.
- Create a sketch
L21_Movesaccording to the template. Writebackward,stopMotorsand movement insetup()himself.
// Шаблон среднего уровня. Напиши код в разделе «Твоя часть» по целям в комментариях.// Функции drive и forward ниже — образец. 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; // ===== Твоя часть: напиши сам ===== void backward(int ms) { // Оба колеса крутятся назад со скоростью speed ms миллисекунд.} void stopMotors() { // Оба мотора стоят.} void setup() { pinMode(LEFT_DIR_PIN, OUTPUT); pinMode(LEFT_SPEED_PIN, OUTPUT); pinMode(RIGHT_DIR_PIN, OUTPUT); pinMode(RIGHT_SPEED_PIN, OUTPUT); stopMotors(); delay(2000); // время убрать руки от робота // Вперёд 1 секунду, остановка, пауза полсекунды, назад 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 forward(int ms) { drive(FORWARD, speed, FORWARD, speed); delay(ms);} void loop() {}
- Find where the functions described and where are they are called. Show it to your partner.
Hint: Back function
How is “backward” different from “forward”? The program already has a constant for this direction.
Hint: How to call a function
Call - function name and parameter value in parentheses, at the end ;.
How it works: How a function with a parameter works
void forward(int ms) - function named forward and the parameter ms. When we write forward(1000), inside a function ms is equal to 1000. So one function can drive at any time.
The program passes the build check without errors. You can show the definition and call of backward.
Requirement 3. Software L21_Moves is built from the functions:
drive(leftDir, leftSpeed, rightDir, rightSpeed)is the only place where the direction and speed of the wheels are set;forward(ms)andbackward(ms)- movement for a specified time,stopMotors()- stop;- the direction "backward" is not written as a number, but is obtained from
FORWARD: on another setFORWARDmay be different; - after turning on there are 2 seconds to remove your hands;
- in
setup(): forward 1 second, stop, pause half a second, backward 1 second, stop.
Hint: Idea (1 of 3)
First there is one general function that sets the direction and speed of both wheels. The remaining functions only call it with the required values.
Hint: Plan (2 of 3)
drive- four lines from your program, but with parameters instead of numbers.forward(ms)—driveforward anddelay(ms).backward(ms)- the same back.stopMotors()- speed 0.
Hint: Code snippet (3 of 3)
const int BACKWARD = (FORWARD == HIGH) ? LOW : HIGH; - read as “if FORWARD is HIGH, then LOW, otherwise HIGH.”
The program fulfills requirement 3 and checks without errors.
First race on the floor
15 minClear space on the floor or table at least a meter in front and back. Keep your hand near the switch.
- Load the program on the stand and check: forward, pause, backward, stop.
- Place the robot on the floor, turn on the power to the motors and press Reset.
- Mark the starting point and the point where the robot stopped on the floor with chalk or tape.
The robot drives forward, stops and returns approximately to the starting point.
| What do you see | What to do |
|---|---|
| The robot is not going straight | The motors are not the same - that's normal. Write down where it leads. |
| The robot returned to the wrong start | The wheels spin forward and backward slightly differently. Write down the difference. |
| The robot drove immediately after loading | That's right: the program starts on its own. Therefore, in setup() there is a pause of 2 seconds. |
- Load the program on the stand and check: forward, pause, backward, stop.
- Place the robot on the floor, mark the start with tape, turn on the power to the motors and press Reset.
- Repeat three times. Each time, mark where the robot stopped, and measure with a ruler how many centimeters it moved forward, backward and sideways from the start.
| Check-in | Forward or backward, cm | Sideways, cm | Where it leads |
|---|---|---|---|
| 1 | |||
| 2 | |||
| 3 |
- Does the robot make the same mistakes in three runs? Write down the conclusion.
Table of three runs and conclusion: where and how much your robot is taking.
| What do you see | What to do |
|---|---|
| The robot is not going straight | The motors are not the same - that's normal. Write down where it leads. |
| The robot drove immediately after loading | That's right: the program starts on its own. Therefore, in setup() there is a pause of 2 seconds. |
Find out how straight your robot is going and try to fix it with one change.
- Test the program on the stand, then place the robot on the floor at the beginning of a meter strip of tape. Drive forward for 2 seconds. Measure how many centimeters the nose moves sideways from the stripe. Repeat three times.
- Suggest one change that will reduce slip: for example, different speeds for the left and right wheels. Write down why you expect improvement.
- Make the change and do three runs again. Has it gotten better? How long?
| Lead 1, cm | Lead 2, cm | Lead 3, cm | |
|---|---|---|---|
| Before | |||
| After |
Hint: Wheels are different
If the robot goes to the right, which wheel spins faster?
Two series of three races, one change with justification and conclusion by numbers.
Change the program
10 min- Make the robot travel forward twice as far and backward as before.
- Do a shuttle: forward and backward three times in a row with pauses.
- Make the robot travel forward twice as far and backward as before.
- Make the robot shuttle three times in a row: forward, stop, backward, stop. Write calls to
forward,stopMotors,backwardonly once. Need a cycleforfrom lesson 1.1.
Will the robot return exactly to the start after three shuttles? Write down your forecast, then mark the start and finish on the floor.
Hint: How for works
for (int i = 0; i < 3; i++) { … } repeats the commands in parentheses three times.
The robot performs both tasks. In the logbook there is a forecast and how far the robot got away from the start after three shuttles.
Requirement 4. Function shuttle(times, ms) does "shuttle" times times: forward ms milliseconds, stop, back, stop. The movement calls are written only once.
Research: how far does a robot travel?
- Run three times
forward(1000)atspeed = 100and measure the path with a ruler in millimeters. Repeat whenspeed = 200. - Calculate how many millimeters per second the robot travels at each speed. How many times do the results differ? How do the numbers differ?
speed? - Find the time
backwardso that after one shuttle the robot stands no further than 2 cm from the start. Write down why forward and backward times turned out different.
speed | Path 1, mm | Path 2, mm | Path 3, mm | mm per second |
|---|---|---|---|---|
| 100 | ||||
| 200 |
Hint: Different paths for the same program
This is normal: the wheels slip, the battery runs out. Therefore, we measure three times and take the average.
shuttle works. In the log there is a table of paths, speed in mm/s for two speed, conclusion about the connection between numbers speed and real speed and selected return time.
The robot moves forward for 1 second, stops and goes back.
Make a shuttle movement with three repetitions by writing calls to forward, stopMotors, backward only once. Hint: loop for from lesson 1.1.
Measure how many millimeters the robot travels per second, and set the time back so that after the shuttle it stands no further than 2 cm from the start. Write down why the time forward and backward are different.
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 drives according to your program. The main thing: analogWrite turns on the motor and it spins until another team stops it. Functions make a program shorter and clearer. In the next lesson the robot will learn to turn.
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
| PWM | Frequent turning on and off of the motor power. A number from 0 to 255 specifies how much time the motor is on. |
| direction | Direction contact state: one value turns the wheel forward, the other turns the wheel backward. |
| constant | A number with a name that does not change while the program is running, for example a contact number. |
| function | Named command block. It can be called many times by writing a name and parentheses. |
| parameter | The number passed to the functions in parentheses, such as the driving time. |