Driving LEDs
An LED is a current-driven device. Applying voltage without limiting current destroys the LED and can damage the GPIO pin.
is the forward voltage: the minimum voltage required for conduction. Below the LED is off. Above , current rises steeply with any small voltage increase.
Typical forward voltages by color:
- Red / yellow: –
- Green / blue / white: –
Current-Limiting Resistor
A series resistor between the GPIO pin and the LED limits current to a safe level.
Here:
- : supply voltage
- : LED forward voltage
- : desired forward current
Typical for indicator LEDs is –. MCU GPIO pins are rated for – depending on the device. must stay within this limit.
Transistor Driver
When exceeds the GPIO current rating, or when driving multiple LEDs, a transistor is placed between the GPIO pin and the LED. The pin drives the transistor base. The transistor supplies current from directly, bypassing the pin’s drive limit.
The GPIO pin sources only , well within pin limits.
Driving 7-Segment Displays
A 7-segment display is 7 individual LEDs (segments a–g) arranged to form digits. Each segment is an independent LED requiring its own current path.
2 variants exist:
- Common cathode
All segment cathodes tied to GND. MCU drives a segment HIGH to light it. - Common anode
All segment anodes tied to . MCU drives a segment LOW to light it (active-low logic).
Per-Segment Resistor
Placing a single resistor in the common line (shared by all segments) causes the current through it to change with the number of active segments.
When segments are on, total current through the shared resistor is:
The voltage drop across the resistor:
Voltage remaining for each segment:
As increases, falls. With enough segments active, drops below , extinguishing segments entirely.
Each segment gets its own series resistor to fix independently of how many other segments are active.
Multiplexing Multiple Digits
Driving each segment of each digit directly requires GPIO pins for digits. Multiplexing reduces this to pins.
Each digit’s corresponding segment pins are wired together across all digits. A separate digit-select line controls a transistor that connects one digit’s common line to GND (common cathode) or (common anode). Only the selected digit’s transistor is active at any time.
Segment pins (a–g) ──────────────────────────────┐
│
Digit 1 common ── transistor ── GND │
Digit 2 common ── transistor ── GND ├── shared segments
Digit 3 common ── transistor ── GND │
Digit 4 common ── transistor ── GND │
↑ │
digit-select GPIO │
Scan sequence per cycle:
- Disable all digit-select lines (all digits off).
- Write segment pattern for digit to the 7 segment GPIO pins.
- Enable digit ‘s select line.
- Hold for the slot duration .
- Advance to the next digit and repeat.
For digits, each digit is on for of the total cycle. Refresh rate per digit must exceed to avoid visible flicker:
The scan loop runs from a timer ISR.
Ghosting
Ghosting occurs when residual segment current lights the wrong digit during a select transition. The cause: segment pins still hold the previous digit’s pattern at the moment the next digit’s select line activates.
Fix: always blank all segment pins (drive all LOW) before enabling the next digit-select line. The blank period adds dead time per slot but eliminates ghost images.
Driving Inductive Loads
Inductive loads (motors, relays, solenoids) store energy in a magnetic field while current flows. When the driving transistor switches off, the magnetic field collapses and induces a voltage spike (back-EMF) in the opposite polarity to the supply.
Spike amplitude depends on and . A fast switch-off generates spikes of tens to hundreds of volts, above the MCU’s rated supply. Without protection, the spike destroys the transistor and can permanently damage the MCU.
Flyback Diode
A diode placed in parallel with the inductive load, reverse-biased under normal operation. When the switch opens and back-EMF reverses polarity, the diode becomes forward-biased and provides a recirculating current path. The stored energy dissipates through the coil resistance rather than spiking onto the supply rail.
V_CC ──┬──────────────┐
│ │ ← flyback diode (cathode to V_CC)
[inductor] ─┼─
│ │
[transistor] │
│ │
GND ───┴──────────────┘
The diode must be placed physically close to the load. A long lead between the load and the diode allows the spike to propagate before the diode clamps it.
Schottky diodes are preferred over silicon for fast loads (PWM motor control). Lower forward voltage and faster recovery reduce power dissipation during high-frequency switching.
Transistor Driver Requirement
MCU GPIO pins cannot drive inductive loads directly. 2 reasons:
- Current
Relay coils and motor windings draw –, far above GPIO limits. - Voltage
Many inductive loads operate at or . GPIO pins are rated to or .
An NPN transistor or N-channel MOSFET is used as the switch. The GPIO pin drives the base or gate. The transistor switches the full load current from the external supply.
DC Motors
A DC motor converts electrical energy to rotational motion. Current through the armature winding produces a magnetic field that reacts against the stator field, generating torque.
Speed is proportional to average voltage. PWM controls speed by varying duty cycle. Motor inertia smooths the switching pulses.
Direction is controlled by reversing current polarity. An H-bridge arranges 4 switches to connect the motor in either supply polarity.
V_CC ──┬─────────────┬──
Q1(high-left) Q3(high-right)
│ │
├────[motor]──┤
│ │
Q2(low-left) Q4(low-right)
GND ───┴─────────────┴──
Operating Modes
- Forward
Q1 + Q4 on, Q2 + Q3 off. Current flows left to right through the motor. - Reverse
Q2 + Q3 on, Q1 + Q4 off. Current flows right to left through the motor. - Brake
Q2 + Q4 on, Q1 + Q3 off. Both motor terminals shorted to GND. The motor’s back-EMF drives current through the winding, producing a braking torque that resists rotation. - Coast
All switches off. Motor terminals float. Motor spins freely with no braking force.
Shoot-Through
Turning on Q1 and Q2 simultaneously (or Q3 and Q4) shorts to GND and instantly destroys the switches.
Shoot-through occurs during switching transitions. If Q1 turns on before Q2 fully turns off, both conduct briefly. A dead time (both switches off) is inserted between turning one switch off and the other on. Dead time is typically – depending on transistor turn-off speed.
PWM Speed Control
PWM is applied to one or both switches on the active side while the opposite low-side switch stays on. The motor sees the average voltage, which scales with duty cycle.
A flyback diode across each transistor is required. Every PWM transition collapses the motor’s inductive field, generating back-EMF. H-bridge ICs include these diodes internally.
Dedicated H-bridge ICs (L298N, DRV8833, TB6612) integrate the 4 transistors, flyback diodes, dead-time control, and logic-level inputs in a single package, accepting direct GPIO drive.
Tachometer
A tachometer measures rotational speed and converts it to an electrical signal the MCU can read. Common implementations:
- Optical encoder
A slotted disc attached to the motor shaft interrupts a light beam. Each slot produces 1 pulse per revolution. A disc with slots produces pulses per revolution. - Hall effect sensor
A magnet on the shaft triggers a Hall sensor on each pass. Contactless. Tolerates dust and oil. - Back-EMF sensing
A spinning DC motor generates a voltage proportional to speed. Measured during PWM off-time when the driver is not switching.
The MCU measures tachometer pulse frequency using a timer in counter or input-capture mode. Speed in RPM:
Here:
- : pulse frequency in Hz
- : pulses per revolution
Closed-Loop Speed Control
Open-loop control sets PWM duty cycle without measuring actual speed. Load changes, supply voltage variation, and motor temperature alter speed with no correction.
Closed-loop control feeds the tachometer reading back to the MCU. The MCU compares measured speed to the setpoint and adjusts the PWM duty cycle to reduce the error.
setpoint ──► [+] ──► controller ──► PWM ──► H-bridge ──► motor
│ │
└──────────────── tachometer ◄────────────────┘
A PID controller computes the correction from 3 terms:
Here:
- : error (setpoint minus measured speed)
- : proportional gain (correction proportional to current error)
- : integral gain (correction for accumulated error, eliminates steady-state offset)
- : derivative gain (correction proportional to rate of error change, damps overshoot)
The controller output maps to PWM duty cycle. On each control loop iteration (driven by a timer ISR), the MCU reads the tachometer, computes the error, updates the PID terms, and writes the new duty cycle to the PWM register.
Stepper Motors
A stepper motor moves in discrete angular steps. Each pulse advances the shaft by a fixed step angle. Position is controlled open-loop with no encoder required.
A common step angle is , giving 200 steps per revolution.
Types
Stepper motors are classified by 2 independent axes: rotor construction and winding configuration.
By Rotor Construction
- Permanent Magnet (PM)
Rotor is a permanent magnet. Stator coils attract and repel the rotor poles. Large step angle: typically or (48–24 steps per revolution). Low cost. Used in low-precision applications such as paper feed in printers. - Variable Reluctance (VR)
Rotor is a toothed soft-iron cylinder with no permanent magnet. Torque is produced by the rotor teeth aligning with the energised stator poles to minimise magnetic reluctance. Step angle as small as . No detent torque when unpowered. Rotor spins freely. - Hybrid
Combines a permanent magnet rotor with toothed stator and rotor poles. The magnet provides detent torque and enhances holding torque. The teeth provide fine angular resolution. Step angle: –. Highest torque and precision of the 3 types. Most common in industrial and 3D printing applications.
By Winding Configuration
- Unipolar
Each coil has a center tap, splitting it into 2 half-windings. Current flows through one half-winding at a time, always in the same direction. The center tap connects to the supply. A single transistor switches each half-winding to GND. 5 wires (4 half-winding ends + 1 common center tap) or 6 wires (separate center taps per coil). A transistor array such as the ULN2003 suffices as the driver. Torque is lower than bipolar because only half the winding is active per step. - Bipolar
2 coils with no center tap. Current direction is reversed through the full winding to produce each magnetic pole. 4 wires (2 per coil). Full winding is active at every step, giving higher torque per frame size than unipolar. Requires an H-bridge per coil to reverse current direction.
Excitation Sequences
The coils must be energised in a specific sequence to advance the rotor. For a 2-coil bipolar motor with coils A and B:
| Step | Coil A | Coil B |
|---|---|---|
| 1 | + | + |
| 2 | − | + |
| 3 | − | − |
| 4 | + | − |
- Full-step (2-phase on)
Both coils energised at each step as above. Maximum torque. - Full-step (wave drive)
1 coil energised at a time. Lower torque. Used to reduce power consumption. - Half-step
Alternates between 1-coil and 2-coil states. Doubles angular resolution to on a motor at the cost of varying torque per step. - Microstepping
Driver varies current amplitude in both coils sinusoidally. Rotor positions between full steps are held by the ratio of currents. Greatly reduces vibration and increases smoothness. Common ratios are 1/8, 1/16, 1/32 step.
Driver Circuits
- Unipolar driver
A transistor array (e.g. ULN2003) switches each half-winding to GND. The center tap connects to the supply. 4 GPIO pins control 4 half-windings directly. - Bipolar driver
Requires 1 H-bridge per coil (2 H-bridges total for a standard 2-coil motor). A dedicated stepper driver IC (A4988, DRV8825) integrates both H-bridges, microstepping current control, and overcurrent protection. The MCU sends only a STEP pulse and a DIR level. The IC handles the excitation sequence internally.
Step Rate and Stall
Speed is proportional to step pulse frequency:
Stepping too fast from standstill stalls the rotor. Step frequency must ramp up from a low starting rate.
Electromagnetic Relays
An EM relay uses a current-driven coil to mechanically actuate a switch. The coil and the switched contacts are electrically isolated. The MCU circuit and the switched load share no common ground.
Structure:
- Coil
Energised by the MCU via a transistor driver. Draws – at or . Coil current must be high enough to generate sufficient magnetic force to pull the armature, and low enough to prevent resistive heating in the coil winding. Both bounds are specified in the relay datasheet as the pull-in current and the maximum continuous coil current. - Armature
Ferromagnetic plate pulled toward the coil core when energised. - Contacts
Mechanically linked to the armature. Rated independently of the coil, typically – at AC or DC. The voltage rating is the maximum voltage the open contacts can block without arcing across the gap. Exceeding it causes the contacts to arc on open, eroding the contact surface and eventually welding them shut.
The coil is an inductive load requiring a flyback diode across its terminals. The diode clamps back-EMF on switch-off and dissipates stored energy through the coil’s own resistance.
V_CC ──┬──────────┐
│ │ (cathode)
[coil] ─┼─ shunt diode
│ │ (anode)
[transistor] │
│ │
GND ───┴──────────┘
Place the diode physically close to the coil. Parasitic inductance in long PCB traces allows the spike to propagate before clamping. A Schottky or fast-recovery diode is preferred.
Single Transistor Driver
An NPN transistor switches the relay coil. The GPIO pin sources a small base current. The transistor sinks the full coil current through its collector.
V_CC ── [coil] ──── collector
NPN
GPIO ── [R_B] ───── base
emitter ── GND
Base resistor limits base current to a safe level while keeping the transistor in saturation:
Choosing to overdrive the transistor ( derated by a factor of 5–10) ensures it stays in saturation across temperature and device variation.
Simple and low-cost. Suitable when the GPIO can source sufficient base current and the coil voltage equals the MCU supply.
Dual Transistor Driver
2 NPN transistors in a Darlington configuration. The emitter of the first (driver) transistor feeds the base of the second (output) transistor. The combined current gain is the product of the 2 stages:
GPIO ── [R_B] ── base(Q1)
NPN Q1
emitter(Q1) ── base(Q2)
NPN Q2
collector(Q2) ── [coil] ── V_CC
emitter(Q2) ── GND
A very small GPIO current drives a relay coil that a single transistor could not switch reliably. Used when:
- The coil current is high relative to the GPIO drive capability
- The MCU operates at a lower voltage than the coil supply, reducing available base drive
Trade-off: the 2 drops in series raise the saturation voltage to , slightly reducing the voltage across the coil.
Darlington arrays such as the ULN2003 integrate 7 Darlington pairs with built-in base resistors and shunt diodes in a single IC, replacing discrete transistor circuits for multi-relay designs.
Contact types:
- NO (Normally Open)
Open when coil is off. Closes when energised. - NC (Normally Closed)
Closed when coil is off. Opens when energised. - SPDT
Provides both NO and NC on 1 common terminal.