Electronics and Arduino

← Robot list · The basics

The electricity every robot runs on, from zero: voltage, current and Ohm's law, batteries and regulators, the Arduino board, sensors, PWM and transistors, the DC motor with its H-bridge and encoder, servos and steppers — and, at the end, a first robot that keeps its distance to a wall. Every circuit is drawn, every program is given in full.

How to use this course

No prerequisite; the Python course helps for the programs. To practise you need an Arduino Uno (or a clone), a breadboard, a few LEDs and resistors, a button, a potentiometer, an HC-SR04, a small DC motor with encoder, a TB6612 or L298N driver, a servo, and a 2S battery with a 5 V buck converter. You can also follow everything on a free online simulator (Wokwi, Tinkercad Circuits) before buying anything.

  • Lessons 1 and 2: electricity and power, the base of everything.
  • Lessons 3 to 7: the Arduino, sensors and every kind of motor.
  • Lesson 8: a complete robot with a closed loop.
1

Voltage, current, resistance and power

25 min
You will learn

what a voltage, a current and a resistance are, Ohm's law U = R I, the power P = U I, how to choose the resistor of an LED, and the voltage divider used to measure a battery.

In one sentence

The voltage pushes, the resistance brakes, and the current is what flows: U = R × I.

1.1 Three quantities

QuantitySymbol, unitPicture with waterIn a robot
voltageU, volt (V)the pressurebattery 7.4 V, logic 5 V or 3.3 V
currentI, ampere (A)the flowan LED 15 mA, a motor 1 A, a servo blocked 2 A
resistanceR, ohm (Ω)a narrow pipe220 Ω for an LED, 10 kΩ for a button
powerP, watt (W)the work done per secondwhat heats a resistor, what a motor gives

U = R I   P = U I = R I²

1.2 The resistor of an LED

An LED always takes about the same voltage (≈ 2 V for red, ≈ 3 V for blue or white) whatever the current, so it cannot limit its own current: without a resistor it burns. The resistor takes the rest of the voltage, and Ohm's law gives its value:

R = (Usupply − ULED) / I = (5 − 2) / 0.015 = 200 Ω → 220 Ω (the next standard value)

1.3 The voltage divider

Two resistors in series share the voltage in proportion to their values. With R1 = R2 = 10 kΩ, a 2S battery full at 8.4 V gives 4.2 V: below the 5 V that an Arduino input accepts, so the robot can watch its battery on A0.

Safety first
  • Never connect + to − directly (a short circuit): a LiPo can then give 50 A and catch fire.
  • Wire with the power off; check the polarity twice before switching on.
  • A resistor has a maximum power (often 0.25 W): check P = R I².

Key terms

  • voltage (V)
  • current (A)
  • resistance (Ω)
  • Ohm's law, U = R I
  • power (W)
  • voltage divider

Exercises

Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.

Level 1 · Beginner1

A red LED (2 V) must take 15 mA from a 5 V pin. Which resistor (in Ω)?

Solution

Rule used R = (U supply − U LED) / I lesson 1 — 1.2 The resistor of an LED

  1. Voltage left for the resistor: 5 − 2 = 3 V.
  2. Current in amperes: 15 mA = 0.015 A.
  3. R = 3 / 0.015 = 200 Ω. The next standard value is 220 Ω (a little less current: 13.6 mA).

Answer 200 Ω → 220 Ω in practice

Level 2 · Intermediate2

What power (in W) does the 220 Ω resistor burn with 13.6 mA? Is a 0.25 W resistor enough?

Solution

Rule used P = R I² lesson 1 — 1.1 Three quantities (the formulas under the table)

StepValue
I0.0136 A
I²0.000185 A²
R I² = 220 × 0.0001850.041 W

Answer 0.041 W: six times less than 0.25 W, so it is enough

Level 2 · Intermediate3

A full 2S battery (8.4 V) goes through a divider R1 = R2 = 10 kΩ to A0. What voltage does A0 get (in V)?

Solution

Rule used voltage divider: Vout = Vin × R2 / (R1 + R2) lesson 1 — 1.3 The voltage divider

  1. R2 / (R1 + R2) = 10 / 20 = 0.5.
  2. Vout = 8.4 × 0.5 = 4.2 V.
  3. Check: 4.2 V < 5 V, the input is safe. In the program: Vbattery = 2 × Vmeasured.

Answer 4.2 V

Check yourself
  1. What current flows through 1 kΩ under 5 V?

    I = U / R = 5 / 1000 = 5 mA.

  2. Why does an LED need a resistor?

    Its voltage hardly changes with the current, so nothing would limit the current: the resistor does it.

  3. With R1 = R2, what fraction of the input voltage do you get at the middle?

    Half: Vout = Vin × R2 / (R1 + R2) = Vin / 2.

2

Batteries and regulators: powering a robot

25 min
You will learn

the batteries of small robots (LiPo, Li-ion, NiMH), their voltage and capacity, how long a robot runs, why the logic and the motors are powered separately, and the difference between a linear regulator and a buck converter.

In one sentence

The battery gives the energy, the regulator makes a clean 5 V for the brain, and the motors take their power directly — with one common ground.

2.1 Batteries

TypeVoltage of one cellStrong pointsCare
LiPo3.7 V (4.2 full, 3.3 empty)light, very high currentspecial charger, never below 3.0 V, fire risk if punctured
Li-ion 186503.6 Vhigh capacity, robust caseprotection board (BMS)
NiMH1.2 Vsafe, cheapheavy, lower current

Cells are put in series to add their voltages: a 2S LiPo = 2 cells = 7.4 V. The capacity in mAh says how long it lasts:

autonomy (h) ≈ capacity (Ah) / average current (A)   2.2 Ah / 1.1 A = 2 h

2.2 One battery, two circuits

  • Motors make big current peaks and electrical noise; if they share the 5 V of the Arduino, it resets when they start.
  • So the logic gets its own regulated 5 V, and the motors are powered by the driver straight from the battery.
  • All the grounds (GND) are connected: a voltage is always measured against a reference, and a signal without a common ground means nothing.

2.3 Linear regulator or buck converter?

Linear (7805, AMS1117)Buck (switching)
howburns the extra voltage as heatswitches fast and stores energy in a coil
lost power(Vin − Vout) × I: (7.4 − 5) × 0.5 = 1.2 W≈ 10 % (efficiency ≈ 90 %)
whensmall currents, very clean voltagebatteries, currents above 0.3 A

Key terms

  • LiPo, cell, 2S
  • capacity (mAh)
  • autonomy
  • regulator
  • buck converter
  • common ground

Exercises

Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.

Level 1 · Beginner1

A robot takes 1.1 A on average from a 2200 mAh battery. How long does it run (in h)?

Solution

Rule used autonomy ≈ capacity / average current, with the capacity in Ah lesson 2 — 2.1 Batteries

  1. 2200 mAh = 2.2 Ah.
  2. 2.2 / 1.1 = 2 h.
  3. In practice, keep 20 % in the LiPo (never empty it): about 1 h 35.

Answer 2 h (≈ 1 h 35 usable)

Level 2 · Intermediate2

A linear regulator makes 5 V from 7.4 V for 0.5 A. How much power does it turn into heat (in W)?

Solution

Rule used lost power of a linear regulator = (Vin − Vout) × I lesson 2 — 2.3 Linear regulator or buck converter? (table)

Value
Vin − Vout2.4 V
× I0.5 A
lost power1.2 W
useful power (5 × 0.5)2.5 W

Answer 1.2 W: one third of the battery power is lost; a buck converter would lose about 0.3 W

Level 1 · Beginner3

What is the voltage of a full 2S LiPo (in V)?

Solution

Rule used cells in series add their voltages; a full LiPo cell = 4.2 V lesson 2 — 2.1 Batteries (table)

  1. 2S = 2 cells in series.
  2. 2 × 4.2 = 8.4 V (7.4 V nominal, 6.6 V empty).

Answer 8.4 V

Check yourself
  1. What is the voltage of a 3S LiPo?

    3 × 3.7 = 11.1 V (12.6 V when full).

  2. Why must the grounds be connected?

    Because a voltage is measured against a reference: without a common ground the Arduino's HIGH means nothing to the driver.

  3. Why does an Arduino reset when the motors start, if they share its 5 V?

    The starting current of the motors makes the 5 V drop for a moment, below what the microcontroller needs.

3

The Arduino: pins, setup, loop and a blinking LED

25 min
You will learn

what is on an Arduino Uno board, the kinds of pins, the structure of a program (setup and loop), how to light an LED, and how to print messages to the computer.

In one sentence

setup() runs once, loop() runs forever: every robot program is built on this pair.

3.1 The board

PinsWhat they doLimits
digital 0–13input or output, HIGH (5 V) or LOW (0 V)20 mA per pin (40 mA absolute maximum); 0 and 1 are used by the USB link
PWM ~ (3, 5, 6, 9, 10, 11)a fast on/off signal: analogWrite (lesson 5)≈ 490 Hz (980 Hz on 5 and 6)
analog A0–A5measure a voltage from 0 to 5 V: analogRead10 bits: 0 … 1023
interrupts 2, 3call a function at once on an edge (encoders)keep the function very short
5 V, 3.3 V, GND, Vinpower for small sensors; Vin takes 7–12 Vnever power a motor from the 5 V pin

3.2 The first program

// blink: the LED on pin 13 turns on and off every half second
const int LED = 13;              // pin 13 (the board's own LED is on it too)

void setup() {                   // runs once, at power-on or reset
  pinMode(LED, OUTPUT);          // pin 13 gives a voltage
  Serial.begin(9600);            // open the link to the computer
}

void loop() {                    // runs again and again, forever
  digitalWrite(LED, HIGH);       // 5 V: the LED is on
  Serial.println("on");
  delay(500);                    // wait 500 ms
  digitalWrite(LED, LOW);        // 0 V: the LED is off
  Serial.println("off");
  delay(500);
}
  1. Install the Arduino IDE (arduino.cc), plug the board with a USB cable.
  2. Choose the board (Arduino Uno) and the port in the Tools menu.
  3. Click Upload (→); the LED blinks once per second.
  4. Open the Serial Monitor at 9600 baud: it prints on, off, on, off…
Same ideas as Python, different words

The Arduino language is C++: each instruction ends with ;, blocks are between { } instead of indentation, and each variable has a declared type (int, float, bool). loop() is the while True: of the Python course, lesson 3.

Key terms

  • microcontroller
  • digital pin, analog pin
  • setup(), loop()
  • pinMode, digitalWrite
  • Serial Monitor

Exercises

Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.

Level 1 · Beginner1

With the blink program, how many times does the LED turn on in 10 s?

Solution

Rule used loop() runs again and again; one turn of loop() = 500 ms on + 500 ms off lesson 3 — 3.2 The first program

  1. One turn of loop() lasts 500 + 500 = 1000 ms = 1 s.
  2. The LED turns on once per turn: 10 s / 1 s = 10 times.

Answer 10 (1 Hz)

Level 2 · Intermediate2

Which pin can give a PWM signal on an Arduino Uno?

  1. pin 2
  2. pin 9
  3. pin 13
  4. A0

Solution

Rule used the PWM pins of the Uno are 3, 5, 6, 9, 10, 11 (marked ~) lesson 3 — 3.1 The board (table)

  1. 2 is an interrupt pin, 13 a plain digital pin, A0 an analog input.
  2. Only 9 is in the list 3, 5, 6, 9, 10, 11.

Answer pin 9 (B)

Check yourself
  1. Which function runs only once?

    setup(), at power-on or after a reset.

  2. Can a pin power a small motor directly?

    No: a pin gives 20 mA at most, a small motor takes hundreds of mA. A transistor or a driver is needed (lessons 5 and 6).

  3. What does delay(500) do?

    It stops the program for 500 ms; nothing else runs meanwhile.

4

Reading sensors: buttons, analog voltages, ultrasound

30 min
You will learn

how to read a button with a pull-up resistor, how to read a voltage with analogRead and turn it into volts, and how an ultrasonic sensor measures a distance from an echo time.

In one sentence

Every sensor finally gives a voltage or a time; the program turns it into a physical quantity with a simple formula.

4.1 A button and its pull-up resistor

An input that is connected to nothing “floats” and reads random values. The pull-up resistor holds it at 5 V; the button, when pressed, connects it to GND. So the logic is inverted: pressed = LOW. INPUT_PULLUP uses the resistor already inside the chip: no extra part.

4.2 An analog voltage

V = n × 5 / 1023   n = analogRead(A0) ∈ [0, 1023]

A potentiometer (a resistor with a slider) between 5 V and GND is a voltage divider you turn by hand: its middle pin gives 0 to 5 V. Light, temperature and battery sensors work the same way.

4.3 Measuring a distance with sound

The HC-SR04 sends a burst of ultrasound when TRIG gets a 10 µs pulse; ECHO then stays HIGH for the time the sound takes to go to the obstacle and come back. Sound travels at 343 m/s = 0.0343 cm/µs:

d = t × 0.0343 / 2   (the 2: there and back)

// a push button (pull-up), a potentiometer and an HC-SR04 ultrasonic sensor
const int BUTTON = 2, TRIG = 9, ECHO = 10;

void setup() {
  pinMode(BUTTON, INPUT_PULLUP); // internal resistor to 5 V: reads HIGH when released
  pinMode(TRIG, OUTPUT);
  pinMode(ECHO, INPUT);
  Serial.begin(9600);
}

float distance_cm() {
  digitalWrite(TRIG, LOW);  delayMicroseconds(2);
  digitalWrite(TRIG, HIGH); delayMicroseconds(10);   // a 10 us pulse starts a measurement
  digitalWrite(TRIG, LOW);
  unsigned long t = pulseIn(ECHO, HIGH, 30000);      // echo time in us (0 if nothing within 30 ms)
  return t * 0.0343 / 2;                             // sound: 343 m/s = 0.0343 cm/us, there and back
}

void loop() {
  bool pressed = digitalRead(BUTTON) == LOW;         // pressed = connected to GND
  int n = analogRead(A0);                            // 0 ... 1023
  float volts = n * 5.0 / 1023;
  Serial.print(pressed ? "pressed  " : "released ");
  Serial.print(volts, 2);  Serial.print(" V  ");
  Serial.print(distance_cm(), 1); Serial.println(" cm");
  delay(200);
}
MeasuredConvertedMeaning
digitalRead(2) = LOWpressedthe button connects the pin to GND
analogRead(A0) = 5122.50 Vthe potentiometer is in the middle
pulseIn = 1166 µs20.0 cman obstacle at 20 cm
Limits of the ultrasonic sensor

Range about 2 cm to 4 m; a soft or slanted surface may send no echo (pulseIn then returns 0 after its timeout); two sensors firing together disturb each other. Lesson 8 shows how the robot handles a missing echo.

Key terms

  • pull-up resistor
  • floating input
  • analogRead, 10 bits
  • potentiometer
  • ultrasonic sensor, echo

Exercises

Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.

Level 1 · Beginner1

analogRead(A0) returns 512. What is the voltage on A0 (in V)?

Solution

Rule used V = n × 5 / 1023 (10 bits: 0 … 1023 for 0 … 5 V) lesson 4 — 4.2 An analog voltage

  1. 512 × 5 = 2560.
  2. 2560 / 1023 = 2.50 V: about half of 5 V.

Answer 2.50 V

Level 2 · Intermediate2

The echo of an HC-SR04 lasts 1166 µs. How far is the obstacle (in cm)?

Hint

The sound goes there and back.

Solution

Rule used d = t × 0.0343 / 2 (sound at 0.0343 cm/µs, there and back) lesson 4 — 4.3 Measuring a distance with sound

StepValue
distance travelled: 1166 × 0.034340.0 cm
divided by 220.0 cm

Answer 20.0 cm

Level 1 · Beginner3

A button is wired to pin 2 and GND, with INPUT_PULLUP. What does digitalRead(2) give when you press it?

  1. HIGH
  2. LOW
  3. a random value
  4. 1023

Solution

Rule used with a pull-up the logic is inverted: released = HIGH, pressed = LOW lesson 4 — 4.1 A button and its pull-up resistor

  1. Released: the resistor holds the pin at 5 V → HIGH.
  2. Pressed: the button connects the pin to GND (0 V) → LOW.

Answer LOW (B)

Check yourself
  1. With INPUT_PULLUP, what does a pressed button read?

    LOW: the button connects the pin to GND.

  2. What voltage does analogRead = 1023 mean?

    5 V, the maximum.

  3. Why divide by 2 in the distance formula?

    Because the echo time is the time to go to the obstacle and come back.

5

PWM and transistors: controlling power

30 min
You will learn

how PWM makes an “average” voltage with a signal that is only on or off, what analogWrite does, why a motor needs a transistor (a MOSFET) and a flyback diode, and how to wire them.

In one sentence

PWM switches the full voltage on and off very fast; the motor only feels the average, set by the fraction of time it is on.

5.1 The duty cycle

duty = value / 255   Uaverage = duty × Usupply

The dashed yellow line is the average. The same PWM dims an LED, sets the speed of a motor or the heat of a resistor. It is efficient: the switch is either fully on (no voltage across it) or fully off (no current), so it hardly heats.

5.2 A transistor as a switch

  • The pin only drives the gate of the MOSFET (almost no current); the motor current flows from the motor supply through the MOSFET to GND.
  • Choose a logic-level MOSFET: fully on with 5 V (or 3.3 V) on the gate.
  • A motor is a coil: when it is switched off, it creates a high voltage spike. The flyback diode, across the motor, lets that current go round and protects the MOSFET.
// PWM: the speed of a DC motor through a MOSFET on pin 5, set by a potentiometer on A0
const int MOTOR = 5;             // a PWM pin (marked ~ on the board)

void setup() {
  pinMode(MOTOR, OUTPUT);
}

void loop() {
  int n = analogRead(A0);        // 0 ... 1023
  int duty = n / 4;              // 0 ... 255
  analogWrite(MOTOR, duty);      // 0 = always off, 255 = always on, 128 = on half the time
  delay(20);
}
One direction only

This circuit can only set the speed. To also choose the direction, four switches are needed: the H-bridge of the next lesson.

Key terms

  • PWM
  • duty cycle
  • analogWrite
  • MOSFET, gate
  • flyback diode

Exercises

Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.

Level 1 · Beginner1

analogWrite(pin, 64): what is the duty cycle (in %)?

Solution

Rule used duty = value / 255 lesson 5 — 5.1 The duty cycle

  1. 64 / 255 = 0.251.
  2. × 100 = 25.1 %: the pin is HIGH a quarter of the time (first line of the figure).

Answer ≈ 25 %

Level 2 · Intermediate2

A motor on 7.4 V is driven with analogWrite 128. What average voltage does it see (in V)?

Solution

Rule used U average = duty × U supply lesson 5 — 5.1 The duty cycle (formula under the figure)

StepValue
duty 128 / 2550.502
× 7.4 V3.71 V

Answer ≈ 3.7 V: the motor turns at about half speed

Level 2 · Intermediate3

Why is a diode placed across a motor driven by a MOSFET?

  1. To make the motor turn faster
  2. To protect the MOSFET from the voltage spike of the coil when it switches off
  3. To choose the direction of rotation
  4. To light up when the motor turns

Solution

Rule used a coil opposes any sudden change of its current; the flyback diode gives that current a path lesson 5 — 5.2 A transistor as a switch (third point)

  1. When the MOSFET opens, the motor current cannot stop at once.
  2. Without a path, the voltage climbs until something breaks: the MOSFET.
  3. The diode lets the current go round through the motor and die out.

Answer B

Check yourself
  1. What duty cycle does analogWrite(255) give?

    100 %: the pin is always HIGH.

  2. Why does the switch of a PWM hardly heat?

    Because it is either fully on (almost no voltage across it) or off (no current): P = U I stays small.

  3. What is the flyback diode for?

    To give a path to the current of the motor coil when the MOSFET opens, so that the voltage spike does not destroy it.

6

The DC motor: H-bridge and encoder

30 min
You will learn

how an H-bridge chooses the direction of a DC motor, how to drive it with a driver board, how an encoder counts the turns and gives the direction, and how to compute the speed of a wheel.

In one sentence

The H-bridge reverses the current to reverse the motor; the encoder counts ticks so that the robot knows how far and how fast its wheels turned.

6.1 The H-bridge

IN1IN2PWMMotor
HIGHLOW0 … 255forward, speed set by PWM
LOWHIGH0 … 255backward
LOWLOW—free wheel (coasts)
HIGHHIGH—brake (motor short-circuited)

Never close S1 and S2 (or S3 and S4) together: that is a short circuit of the battery. Driver boards (TB6612FNG, L298N, DRV8833) contain the four switches and the protections; you only give IN1, IN2 and PWM. The L298N, older, loses about 2 V; the TB6612 almost nothing.

6.2 The encoder

Two signals A and B, shifted by a quarter period (in quadrature). On each rising edge of A, look at B: LOW → one way, HIGH → the other way. An interrupt on A counts the ticks even while loop() is busy.

speed (turns/s) = Δticks / (CPR × Δt)   v = turns/s × π D

// a DC motor through an H-bridge (TB6612 or L298N) and its encoder: direction, PWM, speed
const int PWMA = 5, AIN1 = 7, AIN2 = 8;   // driver: speed and direction
const int ENC_A = 2, ENC_B = 4;           // encoder: A on an interrupt pin
volatile long ticks = 0;
const float CPR = 360.0;                  // ticks per turn of the wheel (encoder x gearbox)

void onA() { ticks += (digitalRead(ENC_B) == HIGH) ? -1 : +1; }   // B tells the direction

void drive(int u) {                       // u from -255 (full back) to +255 (full forward)
  digitalWrite(AIN1, u >= 0 ? HIGH : LOW);
  digitalWrite(AIN2, u >= 0 ? LOW : HIGH);
  analogWrite(PWMA, constrain(abs(u), 0, 255));
}

void setup() {
  pinMode(PWMA, OUTPUT); pinMode(AIN1, OUTPUT); pinMode(AIN2, OUTPUT);
  pinMode(ENC_A, INPUT_PULLUP); pinMode(ENC_B, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(ENC_A), onA, RISING);
  Serial.begin(115200);
}

void loop() {
  static long last = 0;
  drive(150);                              // forward at about 60 %
  delay(100);                              // every 100 ms
  noInterrupts(); long now = ticks; interrupts();
  float rpm = (now - last) / CPR / 0.1 * 60;   // turns per second x 60
  last = now;
  Serial.println(rpm);
}
CPR: count it, do not guess it

CPR is the number of ticks per turn of the wheel = ticks of the encoder per motor turn × gear ratio (× 2 or 4 if both edges are counted). Turn the wheel exactly 10 times by hand and read the count: you get CPR to 0.1 %.

Key terms

  • H-bridge, IN1 / IN2
  • driver board
  • brake, free wheel
  • quadrature encoder
  • interrupt
  • CPR (counts per revolution)

Exercises

Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.

Level 1 · Beginner1

On the H-bridge, S1 and S4 make the motor turn forward. Which switches make it turn backward?

  1. S1 and S2
  2. S3 and S4
  3. S3 and S2
  4. S1 and S3

Solution

Rule used to reverse the motor, reverse the current: close the other diagonal lesson 6 — 6.1 The H-bridge (both figures)

  1. S1 and S2 (or S3 and S4) on the same side: a short circuit of the battery — never.
  2. S1 and S3: both ends of the motor at + 7.4 V, no current.
  3. S3 and S2: the current enters on the right and leaves on the left: backward.

Answer S3 and S2 (C)

Level 2 · Intermediate2

An encoder with CPR = 360 counts 90 ticks in 0.1 s. What is the speed of the wheel (in turns per minute)?

Solution

Rule used turns/s = Δticks / (CPR × Δt) lesson 6 — 6.2 The encoder (formula)

StepValue
turns in 0.1 s: 90 / 3600.25
turns per second: 0.25 / 0.12.5
turns per minute: 2.5 × 60150

Answer 150 turns/min

Level 2 · Intermediate3

The same wheel has a diameter of 65 mm. What is the speed of the robot (in m/s)?

Solution

Rule used v = turns/s × π D (one turn moves the robot by the perimeter of the wheel) lesson 6 — 6.2 The encoder (formula)

  1. Perimeter: π × 0.065 = 0.204 m.
  2. v = 2.5 × 0.204 = 0.51 m/s.

Answer 0.51 m/s

Check yourself
  1. Which switches make the motor turn backward?

    S3 and S2: the current crosses the motor from right to left.

  2. Why use an interrupt for the encoder?

    Ticks come fast and at any time; an interrupt counts each one at once, even during a delay or a print.

  3. How does the encoder give the direction?

    With the second signal B, shifted by a quarter period: its level at each rising edge of A says which way the shaft turns.

7

Servos and stepper motors

25 min
You will learn

how a hobby servo is told an angle with the width of a pulse, how a stepper motor turns by exact steps, microstepping, and how to choose between a DC motor, a servo and a stepper.

In one sentence

A servo goes to an angle and holds it by itself; a stepper turns by exact steps without any sensor.

7.1 The servo

Inside a servo there is a DC motor, a gearbox, a potentiometer that measures the output angle, and a small board that does the control: it compares the angle asked by the pulse with the measured one and drives the motor until they match — the closed loop of lesson 8, already built in.

pulse (ms) = 1 + angle / 180   (1 ms → 0°, 2 ms → 180°; many servos use 0.5–2.5 ms)

7.2 The stepper motor

A stepper has several coils that the driver switches in turn: each pulse on STEP moves the shaft by one step, usually 1.8° (200 steps per turn). With microstepping (1/16 on an A4988) the driver doses the currents to make 3200 smaller steps per turn: smoother and quieter. It needs no encoder as long as it does not skip steps (too much load or too fast).

// a hobby servo on pin 9 and a stepper motor through an A4988 driver (STEP on 3, DIR on 4)
#include <Servo.h>
Servo s;
const int STEP = 3, DIR = 4;

void setup() {
  s.attach(9);                   // a pulse every 20 ms, 1 ms = 0 deg ... 2 ms = 180 deg
  pinMode(STEP, OUTPUT); pinMode(DIR, OUTPUT);
}

void loop() {
  s.write(0);   delay(1000);     // go to 0 deg
  s.write(90);  delay(1000);     // 1.5 ms pulse: the middle
  s.write(180); delay(1000);

  digitalWrite(DIR, HIGH);       // one way
  for (int i = 0; i < 200; i++) {   // 200 full steps = 1 turn (1.8 deg per step)
    digitalWrite(STEP, HIGH); delayMicroseconds(1000);
    digitalWrite(STEP, LOW);  delayMicroseconds(1000);   // 2 ms per step: 1 turn in 0.4 s
  }
  delay(500);
}
DC motor + encoderServoStepper
best forwheels, fast continuous turninga joint of a small arm, a steering3D printers, axes of a gantry, slow precise moves
positionby the encoder and your control loopbuilt-in, about 1°counted steps, open loop
weak pointneeds a controllerlimited range (often 180°), small torqueskips steps if overloaded, draws current even at rest
Power the servos separately

A servo that is blocked can take 1 to 2 A. Several servos on the 5 V pin of the Arduino make it reset: give them their own 5–6 V supply, with the ground common to the Arduino.

Key terms

  • servo, pulse width
  • stepper motor, step angle
  • microstepping
  • skipped steps
  • STEP / DIR driver

Exercises

Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.

Level 1 · Beginner1

Which pulse width (in ms) puts a 1–2 ms servo at 45°?

Solution

Rule used pulse (ms) = 1 + angle / 180 lesson 7 — 7.1 The servo (formula)

  1. 45 / 180 = 0.25.
  2. 1 + 0.25 = 1.25 ms: between the 1 ms of 0° and the 1.5 ms of 90° in the figure.

Answer 1.25 ms

Level 2 · Intermediate2

A 1.8° stepper must turn by 90°. How many full steps?

Solution

Rule used number of steps = angle / step angle lesson 7 — 7.2 The stepper motor

ModeStep angleSteps for 90°Steps per turn
full step1.8°50200
1/16 microstep0.1125°8003200

Answer 50 steps

Check yourself
  1. Which pulse width puts a servo in the middle?

    1.5 ms (90°).

  2. How many full steps make one turn of a 1.8° stepper?

    360 / 1.8 = 200.

  3. Which motor for the wheels of a mobile robot that must know its distance?

    A DC motor with a gearbox and an encoder.

8

A first robot: sense, decide, act

35 min
You will learn

how to put everything together in a small two-wheeled robot that keeps a distance to a wall: the wiring, a loop with a fixed period, a proportional controller with saturation and a dead band, and how to test it safely.

In one sentence

Read the distance, compute the error, command the wheels, twenty times per second: that is a robot.

8.1 The loop

PartPinsLesson
HC-SR04TRIG 9, ECHO 104
TB6612 driver, left wheelPWMA 5, AIN1 7, AIN2 86
TB6612 driver, right wheelPWMB 6, BIN1 11, BIN2 126
2S battery → buck 5 V → Arduino; battery → VM of the driverall GND together2

8.2 The proportional controller

e = d − 20 cm   u = Kp e, limited to ±200   u = 0 if |e| < 1 cm

  • Too far (e > 0): the robot goes forward; too close (e < 0): it goes back; the bigger the error, the faster.
  • The saturation at ±200 keeps the speed reasonable and the PWM inside 0…255.
  • The dead band of ±1 cm stops the robot from buzzing back and forth around the target because of sensor noise.
  • millis() gives a fixed period of 50 ms without delay(), so the loop could do other things in between.
// a first robot: two wheels keep the robot 20 cm from a wall with a proportional controller
const int TRIG = 9, ECHO = 10;
const int PWMA = 5, AIN1 = 7, AIN2 = 8, PWMB = 6, BIN1 = 11, BIN2 = 12;
const float TARGET = 20.0, KP = 12.0;     // cm, PWM units per cm
const unsigned long PERIOD = 50;          // ms: the loop runs at 20 Hz

float distance_cm() {
  digitalWrite(TRIG, LOW);  delayMicroseconds(2);
  digitalWrite(TRIG, HIGH); delayMicroseconds(10); digitalWrite(TRIG, LOW);
  unsigned long t = pulseIn(ECHO, HIGH, 30000);
  return t == 0 ? 400 : t * 0.0343 / 2;   // no echo: treat as far away
}

void wheel(int pwm, int in1, int in2, int u) {
  digitalWrite(in1, u >= 0 ? HIGH : LOW); digitalWrite(in2, u >= 0 ? LOW : HIGH);
  analogWrite(pwm, constrain(abs(u), 0, 255));
}

void setup() {
  int outs[] = {TRIG, PWMA, AIN1, AIN2, PWMB, BIN1, BIN2};
  for (int p : outs) pinMode(p, OUTPUT);
  pinMode(ECHO, INPUT);
  Serial.begin(115200);
}

void loop() {
  static unsigned long next = 0;
  if (millis() < next) return;            // wait for the next period without blocking
  next = millis() + PERIOD;

  float d = distance_cm();                // 1. read
  float e = d - TARGET;                   // 2. compute: error > 0 = too far, go forward
  int u = constrain((int)(KP * e), -200, 200);
  if (abs(e) < 1.0) u = 0;                //    a dead band: no buzzing around the target
  wheel(PWMA, AIN1, AIN2, u);             // 3. command both wheels
  wheel(PWMB, BIN1, BIN2, u);
  Serial.print(d); Serial.print(" cm  u = "); Serial.println(u);
}
Test it step by step
  1. Wheels in the air: print d and u, move your hand in front of the sensor, check the signs.
  2. One wheel at a time: u = 100 must turn it forward; if not, swap AIN1 and AIN2 in the code (or the motor wires).
  3. On the floor with a small Kp (4), then increase it until the robot oscillates, and take half of that value.
  4. Keep a hand near the switch: a sign error makes the robot run into the wall.
Where to go next

Add the encoders of lesson 6 and a PI loop on each wheel speed (control course), a line sensor or a second sonar to follow a wall, then move the “brain” to a Raspberry Pi with ROS 2 while the Arduino keeps the fast motor loops.

Key terms

  • closed loop
  • error, target
  • saturation
  • dead band
  • fixed period, millis()

Exercises

Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.

Level 1 · Beginner1

The robot reads d = 30 cm (target 20 cm, Kp = 12). What command u does it send?

Solution

Rule used e = d − target, u = Kp e, limited to ±200 lesson 8 — 8.2 The proportional controller

StepValue
e = 30 − 2010 cm
u = 12 × 10120
|u| ≤ 200?yes: no saturation

Answer u = 120: forward at about half speed (120 / 255)

Level 2 · Intermediate2

Same robot, d = 50 cm. What command u does it send?

Hint

Do not forget the limit.

Solution

Rule used saturation: u is limited to ±200 (constrain) lesson 8 — 8.2 The proportional controller (figure and list)

  1. e = 50 − 20 = 30 cm.
  2. Kp e = 12 × 30 = 360.
  3. 360 > 200, so constrain gives 200: the flat part of the curve.

Answer u = 200

Level 1 · Beginner3

The loop runs every 50 ms. How many times per second does the robot read its sensor?

Solution

Rule used frequency = 1 / period lesson 8 — 8.1 The loop

  1. Period = 50 ms = 0.05 s.
  2. 1 / 0.05 = 20 Hz.
  3. Check: the echo can last up to 30 ms (timeout), so 50 ms leaves enough time.

Answer 20 times (20 Hz)

Check yourself
  1. What does the robot do at d = 15 cm?

    e = −5, u = 12 × (−5) = −60: it backs up slowly.

  2. Why a dead band?

    So that the noise of the sensor (±0.5 cm) does not make the wheels go back and forth around the target.

  3. What does the code do when no echo comes back?

    distance_cm() returns 400 cm (far away): the robot goes forward at the limited speed of 200 instead of reading 0 and backing up.

Glossary

All the words of the course in one place.

TermMeaning
Voltage (V)The electrical “pressure” between two points.
Current (A)The flow of charges through a wire.
Ohm's lawU = R I.
Voltage dividerTwo resistors that give a fraction of a voltage: Vout = Vin R2 / (R1 + R2).
Common groundThe 0 V reference shared by every part of the robot.
Regulator, buck converterA circuit that makes a fixed lower voltage (5 V) from the battery.
Pull-up resistorHolds an input at 5 V when nothing pulls it down.
PWM, duty cycleA fast on/off signal; the fraction of time on sets the average voltage.
MOSFETA transistor used as an electronic switch for a big current.
Flyback diodeProtects the switch from the voltage spike of a coil.
H-bridgeFour switches that set the direction of a DC motor.
Encoder, CPRA sensor that gives ticks as a shaft turns; CPR = ticks per turn.
ServoA motor with its own position loop, told an angle by a 1–2 ms pulse.
Stepper motorA motor that turns by exact steps (often 1.8°).
Saturation, dead bandA limit on the command; a small zone around the target where the command is zero.

Sources and references

This course was written from these books, papers, standards and documentation. They are also the best way to go further.

  1. P. Horowitz, W. Hill, The Art of Electronics, 3rd ed., Cambridge University Press, 2015. used for: Ohm's law, dividers, regulators, transistors, diodes
  2. Arduino documentation and language reference, docs.arduino.cc; ATmega328P datasheet, Microchip. used for: pins, analogRead, analogWrite, interrupts, limits of the board
  3. HC-SR04 ultrasonic ranging module, datasheet (Elecfreaks). used for: the ultrasonic sensor
  4. Toshiba TB6612FNG dual motor driver, datasheet; Allegro A4988 stepper driver, datasheet. used for: the H-bridge and stepper drivers
  5. R. Siegwart, I. R. Nourbakhsh, D. Scaramuzza, Introduction to Autonomous Mobile Robots, 2nd ed., MIT Press, 2011. used for: encoders and the first mobile robot
  6. K. J. Åström, R. M. Murray, Feedback Systems: An Introduction for Scientists and Engineers, 2nd ed., Princeton University Press, 2021 (free online). used for: the proportional controller

Your first robot moves on its own!

Next: the control course to turn the P controller into a PID on each wheel, the wheeled mobile robots course for odometry and path following, and ROS 2 from zero to give the robot a bigger brain.

Back to the roadmap → Home page