Sensors & Motors
Read the world with sensors, then make it move.
Sensors & Motors
Sense the world, then move it
Navigate with ← → or Space · F to present fullscreen · N for the script
Lesson notes
The big practical day: how sensors turn the world into data (LDR, IR, pull-ups, the line follower), then driving motors — PWM speed, H-bridges, servos, ultrasonic distance, and ESP32 Bluetooth.
Sensors & Motors
Sense the world, then move it
- How sensors work · LDR · IR
- Pull-up / pull-down
- Line-following robot
- Motors & drivers
- PWM speed · H-bridge
- Servo · ultrasonic
- ESP32 Bluetooth
How Sensors Detect the Environment
A sensor is a transducer: it converts a physical quantity into an electrical signal.
Light, temperature, distance, motion → voltage, resistance, or a digital pulse the microcontroller can read.
Map each sensor we use to what it converts: LDR → resistance, IR → reflected pulse, thermistor → resistance.
Two output styles
Analog out
- Gives a continuous voltage
- Read with analogRead()
- LDR, potentiometer, many gas sensors
Digital out
- Gives HIGH/LOW (or a protocol)
- Read with digitalRead() or a library
- IR module, PIR, ultrasonic
Example: the DHT temperature & humidity sensor
A common digital sensor — it measures temperature and humidity and sends the reading to one data pin as a digital signal.
- Single-wire digital output
- A library decodes the timing for you
- DHT11 (basic) / DHT22 (more accurate)
Sensor Circuit Design
The voltage divider
Many sensors change resistance. A divider (sensor + fixed resistor) turns that changing resistance into a changing voltage the ADC can read.
- Vout = Vin × R2 / (R1 + R2)
- Sensor resistance shifts → Vout shifts
- The MCU reads Vout with analogRead()
LDR — Light Dependent Resistor
Read brightness with a voltage divider
- Resistance drops as light increases
- Pair with a 10 kΩ resistor to ground for a clean reading
// LDR + 10k resistor form a divider into pin 34
int light = analogRead(34); // bright = high, dark = low
Serial.println(light);
if (light < 800) {
digitalWrite(ledPin, HIGH); // dark → turn light on
}The LDR (photoresistor)
That squiggly face is light-sensitive material — its resistance falls as more light hits it.
- Bright light → low resistance
- Darkness → high resistance
- No polarity — connect either way
IR — Infrared Sensor
Inside an IR sensor module
Two facing LEDs: one emits invisible infrared, the other (black) receives what bounces back. A trim-pot sets the threshold.
- Emitter + receiver pair
- Trim-pot tunes sensitivity
- 3 pins: VCC · OUT · GND
IR reflective sensing
An IR LED emits infrared; a photodiode reads what bounces back.
How it reads surfaces
- White/shiny reflects → detected
- Black/matte absorbs → not detected
- Most modules output a clean digital HIGH/LOW
Uses
- Line-following robots
- Obstacle detection
- Encoder wheels & counters
Why black vs white matters
The same sensor reads different surfaces: a white surface bounces the beam back (detected), a black surface soaks it up (nothing returns).
- White → reflects → OUT goes HIGH/green
- Black → absorbs → OUT goes LOW/red
- This is exactly how line-following works
Watch the surface flip white↔black and the OUT indicator follow it.
Read an IR module
int ir = digitalRead(IR_PIN);
if (ir == LOW) { // line detected (module-dependent)
Serial.println("On the line");
}A trim-pot on most IR modules sets the detection threshold — calibrate it before relying on it.
Pull-up / Pull-down Resistors
Stop the pin from floating
An unconnected input "floats" and reads random noise. A pull-up resistor ties it HIGH when idle; a pull-down ties it LOW.
The ESP32/Arduino have built-in pull-ups: pinMode(pin, INPUT_PULLUP). Then the button connects the pin to GND.
LED Current-Limiting Resistor
Always size the resistor
R = (V_supply − V_LED) / I_LED
- V_supply — your source voltage
- V_LED — LED forward voltage (~2 V red, ~3 V blue)
- I_LED — desired current (~10–20 mA)
Example: (5 V − 2 V) / 0.01 A = 300 Ω → use 330 Ω. Without it the LED burns out.
Zener Diode — Voltage Regulation
A Zener diode clamps voltage to a fixed value.
Wired in reverse, it conducts once voltage reaches its rated "Zener voltage", holding the node steady. A simple way to make a stable reference or protect an input from over-voltage.
Contrast with the 7805 linear regulator coming on Day 7 — Zener is cheap/simple but low-current.
Motor Types & Drivers
Three motors you will use
- DC motor: Spins continuously; speed by voltage/PWM, direction by polarity.
- Servo: Moves to a precise ANGLE (0–180°). Has built-in control electronics.
- Stepper: Rotates in exact steps for precise positioning — printers, CNC.
Never drive a motor straight from an MCU pin.
A pin supplies a few mA; a motor needs hundreds. A driver IC (L298N, L293D, DRV8833) takes your small logic signal and switches the big motor current — and isolates the MCU from electrical noise.
Motors, drivers & sensors
The moving parts and the chips that drive them.
- DC motor — spins freely
- Servo (SG90) — moves to an angle
- Stepper — exact steps
- L298 driver — switches motor power
- HC-SR04 — ultrasonic distance
PWM Speed Control
Set motor speed with PWM
- Duty cycle sets average power → speed
- The two IN pins set spin direction
// ESP32 LEDC PWM on the driver's enable pin
ledcAttach(enablePin, 1000, 8); // 1 kHz, 8-bit
ledcWrite(enablePin, 128); // 50% speed (0–255)
// Direction via two input pins
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW); // forwardH-Bridge Operation
How an H-bridge reverses a motor
Four switches form an "H". Closing the diagonal pairs sends current one way or the other — that flips motor direction.
Warning: never turn on both switches on the same side — that shorts the supply ("shoot-through").
Servo Motors
Sweep a servo 0 → 180°
- write(angle) commands a position, not a speed
- Servos use a PWM pulse width to encode the angle
#include <ESP32Servo.h>
Servo s;
void setup(){ s.attach(18); }
void loop(){
for (int a = 0; a <= 180; a++){ s.write(a); delay(15); }
for (int a = 180; a >= 0; a--){ s.write(a); delay(15); }
}A servo moves to an angle
Unlike a DC motor that spins freely, a servo rotates to a precise commanded angle and holds it.
- write(0) → write(180) sweeps the arm
- Internal electronics hold the position
- Great for steering, arms, grippers
Ultrasonic Sensor (HC-SR04)
Distance by echo timing
The sensor sends an ultrasonic pulse and times how long the echo takes to bounce back off an object.
- distance = time × 0.0343 cm/µs ÷ 2
- Divide by 2 — sound makes a round trip
- pulseIn() measures the echo time
Measure distance by echo timing
- Send a pulse, time how long the echo takes back
- Distance = (time × speed of sound) / 2
digitalWrite(trig, HIGH); delayMicroseconds(10);
digitalWrite(trig, LOW);
long us = pulseIn(echo, HIGH); // echo travel time
float cm = us * 0.0343 / 2; // speed of sound
Serial.println(cm);For multiple sensors, fire them one at a time so echoes do not cross-talk.
IR Line Detection & Calibration
A line-following robot in action
The whole point of IR line sensing: a robot that drives itself along a track by constantly checking which sensors see the black line.
- IR sensors point down at the floor
- Line under a side sensor → steer that way
- Loop fast → smooth following
This is the classic first-robot project — the bot follows the curve on its own.
Building a line follower
- Mount IR sensors facing the floor — usually two or more across the line
- Calibrate the threshold — read values over black AND white, pick the midpoint
- Steer from the difference — left sensor sees line → turn left, and vice versa
- Tip — consistent lighting and sensor height matter more than code
ESP32 Bluetooth Classic
Control over Bluetooth Serial
- Pair from a phone app, send characters as commands
- SerialBT works just like the USB Serial you already know
#include "BluetoothSerial.h"
BluetoothSerial SerialBT;
void setup(){ SerialBT.begin("ElectroBot"); }
void loop(){
if (SerialBT.available()){
char c = SerialBT.read();
if (c == 'F') forward();
if (c == 'S') stop();
}
}Day 4 — Key Takeaways
- Sensors convert the world into electrical signals
- Resistive sensors need a voltage divider; pull-ups stop floating inputs
- IR reflects off white, absorbs on black — the basis of line following
- Motors always need a driver, never a bare MCU pin
- PWM duty cycle = speed; an H-bridge sets direction
- Servos take an angle; HC-SR04 measures distance by echo
- ESP32 Bluetooth Serial = wireless control with familiar code