The Embedded Systems and Electronics Picture Book
Sensorstemperaturelight · motionbuttons inputs MCUCPU · memoryGPIO · timers outputs ActuatorsLEDsmotors · servosdisplays · buzzer Power: 3.3 V / 5 V A tiny dedicated computersense → decide → act, in a loop, forever · thermostats, drones, washing machines, wearables
PLATE 0 — Read the world, run a small program, and change the world back.
A picture book for grown-ups · with circuits and code

Embedded Systems and Electronics

Nine spreads: electricity basics, components, microcontrollers, Arduino and ESP32 programming, sensors, communication buses, timing and interrupts, Raspberry Pi, and building a real project.

Say it like a pro

"An ESP32 reads an I²C sensor, filters the data, drives a MOSFET-switched load, sleeps between samples, and reports over MQTT."

Low voltages only. Use the tabs or the ← → keys.

Water analogy Voltage (V) = pressureCurrent (I) = flow rateResistance (R) = narrow pipemore pressure → more flow VIR V = I × R 5 V 220 Ω LED I = (5 V − 2 V LED) ÷ 220 Ω ≈ 14 mA · always use a resistor with an LED power P = V × I (watts) · resistors in series add, in parallel combine
PLATE 1 — Voltage pushes, resistance limits, current is what flows.
Chapter 1 · Electricity basics

Voltage, current, resistance

volt (V)
electrical pressure: USB 5 V, most MCUs 3.3 V, batteries 1.5–4.2 V
amp (A)
flow; hobby parts use milliamps (mA)
ohm (Ω)
resistance; V = I × R
watt (W)
power P = V × I; resistors have wattage limits (¼ W typical)
DC vs AC
steady (batteries, USB) vs alternating (mains: dangerous. Don't open mains-powered devices.)
ground (GND)
the common reference; everything in a circuit must share it
Example: LED needs ~2 V and 10–20 mA, supply is 5 V
R = (V_supply − V_led) / I = (5 − 2) / 0.015 = 200 Ω  → use 220 Ω (the next standard value)

Voltage divider (read a 5 V signal safely with a 3.3 V pin):
Vout = Vin × R2 / (R1 + R2)    e.g. R1 = 1 kΩ, R2 = 2 kΩ → 5 V → 3.33 V
  • Never connect a battery directly across an LED, motor, or itself: a short circuit makes heat fast.
  • Multimeter first: check voltage, continuity and resistance before blaming the code.
  • Breadboard: rows are connected in strips; power rails run along the sides.
Say it like a pro

"I sized the series resistor with Ohm's law, and checked the rail with a multimeter before powering the MCU."

Resistorlimits currentpull-up / divider Capacitorstores chargedecouples noise Diode / LEDone-way valveflyback protection MOSFET / BJTelectronic switch:small signal → big load Button + pull-updefines a pin's levelwhen not pressed Potentiometervariable resistoranalog knob input Rules of thumb LED → series resistor, always · inductive load (motor, relay) → flyback diode across it MCU pins supply only ~10–40 mA: use a transistor or MOSFET driver for motors, strips, relays add 0.1 µF decoupling capacitors close to every IC's power pins read the datasheet: absolute maximum ratings are not operating values
PLATE 2 — A dozen kinds of parts cover most hobby projects.
Chapter 2 · Components

The parts drawer, and what each does

PartUseTypical value
resistorcurrent limit, pull-up, divider220 Ω · 10 kΩ
electrolytic capsmooth power rails100–470 µF
ceramic capdecoupling0.1 µF
1N4007 / 1N4148protection / signal diode—
2N2222 / IRLZ44NNPN transistor / logic-level MOSFET—
AMS1117-3.35 V → 3.3 V regulator≤ 800 mA
pull-up / pull-down
a resistor (≈10 kΩ) that holds a floating input at HIGH / LOW. MCUs have built-in ones.
logic level
3.3 V and 5 V devices on one bus need level shifting; don't feed 5 V into a 3.3 V pin
PCB / breadboard / perfboard
prototype on breadboard, then solder, then design a PCB (KiCad is free)
Motor driven by an MCU pin (low-side switch):
  MCU pin ──[220 Ω]── gate of logic-level N-MOSFET
  motor + ── supply +      motor − ── drain      source ── GND (shared with MCU)
  flyback diode across the motor: stripe (cathode) toward supply +
  [100 kΩ gate pull-down so it stays off while the MCU boots]
Say it like a pro

"A logic-level MOSFET switches the motor, a flyback diode protects it, and the grounds are shared."

One chip: microcontroller (MCU) CPU core Flash (code) RAM Timers/PWM GPIO pins ADC / DAC UART · I²C · SPI · USB · Wi-Fi/BT program, memory and I/O all inside Popular boards Arduino Uno (ATmega328, 5 V, 32 KB flash) · Raspberry Pi Pico (RP2040) · ESP32 (Wi-Fi + BLE) STM32 (professional-grade ARM) · nRF52 (Bluetooth LE) · Raspberry Pi (a full Linux computer) MCU: runs one program, real-time, milliwatts · SBC: runs an OS, more power-hungry
PLATE 3 — Everything a tiny computer needs, on a chip that costs a dollar or two.
Chapter 3 · Microcontrollers

Pick a board and blink an LED

// Arduino IDE or PlatformIO. The classic first program
const int LED = 13;                         // pin number (LED_BUILTIN on most boards)

void setup() {                              // runs once at power-up
  pinMode(LED, OUTPUT);
  Serial.begin(115200);                     // talk to the computer over USB
}

void loop() {                               // runs forever
  digitalWrite(LED, HIGH); delay(500);
  digitalWrite(LED, LOW);  delay(500);
  Serial.println("blink");
}
$ pip install platformio                   # pro-grade CLI toolchain (or use VS Code + PlatformIO)
$ pio project init --board esp32dev
$ pio run -t upload ; pio device monitor -b 115200
# or Arduino CLI
$ arduino-cli core install arduino:avr ; arduino-cli compile --fqbn arduino:avr:uno blink ; arduino-cli upload -p COM3 --fqbn arduino:avr:uno blink
# MicroPython on a Pico / ESP32: the same thing in Python
from machine import Pin
import time
led = Pin(2, Pin.OUT)
while True:
    led.toggle(); time.sleep(0.5)
flash / RAM
program storage (non-volatile) vs variables (lost at power-off); both are tiny, so avoid wasting RAM
bootloader
small program that lets USB upload your code
Say it like a pro

"I prototype on an ESP32 with PlatformIO, and move to MicroPython only when speed isn't critical."

Digital: HIGH / LOW Analog → ADC number 0–4095 PWM: fake an analog level 25% duty → dim 75% duty → bright Pin modes INPUT · INPUT_PULLUP (button to GND) · OUTPUT · analog input · PWM output buttons bounce: debounce in software (~20 ms) or hardware (RC filter) ADC reads are noisy: average several samples · ESP32 ADC is non-linear, calibrate if precision matters
PLATE 4 — Pins read or write voltages. PWM and ADC bridge digital and analog.
Chapter 4 · GPIO, analog & PWM

Buttons, knobs, and dimmers

const int BTN = 4, LED = 5, POT = 34;       // ESP32 pins; check your board's pinout

void setup() {
  pinMode(BTN, INPUT_PULLUP);               // pressed = LOW (wired to GND)
  ledcAttach(LED, 5000, 8);                 // ESP32 PWM: 5 kHz, 8-bit (0–255)
}

bool lastPressed = false; unsigned long lastChange = 0;
bool ledOn = false;

void loop() {
  // read the knob and map it to brightness
  int raw = analogRead(POT);                // 0–4095 on ESP32 (12-bit)
  int duty = map(raw, 0, 4095, 0, 255);

  // debounced button toggles the LED on/off
  bool pressed = digitalRead(BTN) == LOW;
  if (pressed != lastPressed && millis() - lastChange > 25) {
    lastChange = millis(); lastPressed = pressed;
    if (pressed) ledOn = !ledOn;
  }
  ledcWrite(LED, ledOn ? duty : 0);
}
millis()
time since boot; use it instead of delay() so the loop stays responsive
servo
PWM pulse width (1–2 ms every 20 ms) sets the angle
never
drive motors or long LED strips directly from a pin
Say it like a pro

"Pull-ups with software debounce, a non-blocking loop built on millis(), and PWM for brightness."

I²C · 2 wires, many devices, addresses MCU SDASCL 0x76 BME 0x3C OLED 0x68 IMU SPI · fast, 4 wires MOSI · MISO · SCK + a CS pin per deviceSD cards, displays, radiosMHz speeds · no addresses UART · 2 devices, async TX → RX and RX → TX, shared GNDGPS, Bluetooth modules, serial debugboth sides agree on the baud rate I²C needs pull-up resistors (≈4.7 kΩ) on SDA and SCL breakout boards often include them · two devices with the same address clash
PLATE 5 — Sensors speak a few standard languages over a few wires.
Chapter 5 · Sensors & communication buses

I²C, SPI, and UART in practice

#include <Wire.h>
#include <Adafruit_BME280.h>       // temperature · humidity · pressure over I²C

Adafruit_BME280 bme;

void setup() {
  Serial.begin(115200);
  Wire.begin(21, 22);               // ESP32 default SDA, SCL
  if (!bme.begin(0x76)) { Serial.println("BME280 not found: check wiring and address"); while (true) delay(1000); }
}

void loop() {
  Serial.printf("%.1f °C  %.0f %%RH  %.0f hPa\n", bme.readTemperature(), bme.readHumidity(), bme.readPressure() / 100.0F);
  delay(2000);
}
// I²C scanner: which addresses answer?
for (byte a = 1; a < 127; a++) { Wire.beginTransmission(a); if (Wire.endTransmission() == 0) Serial.printf("found 0x%02X\n", a); }
SensorMeasuresBus
BME280temp, humidity, pressureI²C / SPI
MPU6050acceleration, gyroI²C
HC-SR04distance (ultrasonic)GPIO pulse
NEO-6MGPS positionUART
DHT22temp, humidityone-wire style
Say it like a pro

"I scanned the I²C bus to confirm the address, then checked pull-ups and voltage levels before blaming the library."

Pollingloop() asks "pressed yet?"can miss short pulseswhile busy elsewhere Interrupthardware taps the CPU's shoulderpause → handler → resumekeep handlers tiny and fast State machine: a traffic light GREEN YELLOW RED 5 s2 s6 s model behaviour as states + events + transitions: clear, testable, no delay() maze
PLATE 6 — Don't busy-wait. React to events, and structure the program as states.
Chapter 6 · Timing, interrupts & state machines

Responsive firmware

volatile bool pulse = false;                    // shared with the ISR → volatile
volatile uint32_t pulses = 0;

void IRAM_ATTR onPulse() { pulses++; pulse = true; }     // ISR: do almost nothing

void setup() {
  pinMode(27, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(27), onPulse, FALLING);
}
void loop() {
  if (pulse) { noInterrupts(); uint32_t n = pulses; pulse = false; interrupts(); Serial.println(n); }
}

// non-blocking timing and a state machine
enum State { GREEN, YELLOW, RED } state = GREEN;
unsigned long since = 0;
const unsigned long DUR[] = { 5000, 2000, 6000 };
void loop2() {
  if (millis() - since >= DUR[state]) { state = (State)((state + 1) % 3); since = millis(); setLights(state); }
}
  • ISRs: set a flag, increment a counter, return. No Serial.print, no delay.
  • Hardware timers trigger work at exact intervals; watchdog timers reset the chip if the program hangs.
  • RTOS (FreeRTOS) runs several tasks with priorities when one loop gets too tangled; ESP32 includes it.
  • Overflow: millis() wraps (~49 days on 32-bit); write now - then >= interval, which handles it.
Say it like a pro

"Short interrupt handlers that set flags, non-blocking timing with millis(), a watchdog enabled, and a state machine for behaviour."

wakedeep sleep ~10 µAtime → awake: ~80 mA for 2 s Average current decides battery life (80 mA × 2 s + 0.01 mA × 598 s) / 600 s ≈ 0.27 mA → a 2000 mAh cell ≈ 300 days sleep more, wake less, turn radios off, lower clock speed, use efficient regulators
PLATE 7 — Battery projects live or die by how much of the time the chip is asleep.
Chapter 7 · Power & low-power design

Make a battery last months

#include <esp_sleep.h>
RTC_DATA_ATTR int bootCount = 0;               // survives deep sleep

void setup() {
  bootCount++;
  float t = readSensor();                      // quick measurement
  sendOverWiFiOrLoRa(t);                       // the expensive part: keep it short
  esp_sleep_enable_timer_wakeup(10ULL * 60 * 1000000);   // wake in 10 minutes (microseconds)
  esp_deep_sleep_start();                      // ~10 µA; the chip restarts from setup()
}
void loop() {}
SourceNotes
USB 5 V500 mA typical; easy for development
Li-ion / LiPo 3.7 Vneeds a charger and protection circuit; never short or puncture
2×AA / AAAsimple, low drain; voltage sags as it drains
solar + supercap/LiPofor outdoor sensors; add a charge controller
LDO vs buck
linear regulator wastes the voltage drop as heat; a buck converter is efficient
measure
use a multimeter in series, or a power profiler (Nordic PPK2 / INA219 module) to see wake spikes
safety
lithium cells can start fires: use protected cells and proper chargers
Say it like a pro

"Deep sleep between samples, radio only briefly, an efficient regulator, and current measured, not guessed."

ESP32 + sensor ESP32 + relay MQTT Raspberry PiMosquitto brokerNode-RED · DB DashboardGrafana · phone Pi vs microcontroller Pi: full Linux, Python, cameras, networking, SD card · needs clean shutdown, ~2–5 W MCU: instant on, real-time, microwatts when sleeping · simple and cheap Connectivity Wi-Fi / BLE (ESP32) · LoRa (km range, tiny data) · Zigbee/Thread · cellular (NB-IoT) Secure it TLS + per-device credentials · no default passwords · signed updates (OTA) · isolate IoT VLAN
PLATE 8 — Small devices report to a broker; the broker feeds everything else.
Chapter 8 · IoT & Raspberry Pi

Connect devices to the network

// ESP32: publish a reading every 30 s over MQTT (PubSubClient library)
#include <WiFi.h>
#include <PubSubClient.h>
WiFiClient net; PubSubClient mqtt(net);

void setup() {
  WiFi.begin(WIFI_SSID, WIFI_PASS);             // keep credentials in a git-ignored secrets.h
  while (WiFi.status() != WL_CONNECTED) delay(250);
  mqtt.setServer("192.168.1.50", 1883);
}
void loop() {
  if (!mqtt.connected()) mqtt.connect("esp32-garden");
  mqtt.loop();
  char msg[32]; snprintf(msg, sizeof msg, "%.1f", readTemp());
  mqtt.publish("home/garden/temperature", msg);
  delay(30000);
}
# Raspberry Pi: broker, subscribe, GPIO from Python
$ sudo apt install mosquitto mosquitto-clients
$ mosquitto_sub -h localhost -t 'home/#' -v
$ mosquitto_pub -h localhost -t home/garden/pump -m ON
$ pinout                                       # the Pi's header diagram
$ python3 - <<'EOF'
from gpiozero import LED, Button
led, btn = LED(17), Button(2)
btn.when_pressed = led.toggle
input("press Enter to quit")
EOF
Say it like a pro

"MQTT with TLS and per-device credentials, devices on an isolated VLAN, and signed OTA updates."

1 · power: right voltage, polarity, common ground? 2 · wiring vs the pinout (not the printed label) 3 · multimeter: continuity, voltages at the pins 4 · serial prints: does the code reach this line? 5 · logic analyzer / scope: what's on the wire? Change one thing at a timetest each part alone (sensor, display, motor) before combining them
PLATE 9 — Most "software bugs" in hardware projects are power or wiring.
Chapter 9 · Building & debugging a project

A weather station, start to finish

  1. Parts: ESP32 dev board, BME280, 0.96″ OLED (I²C), breadboard, jumper wires, USB cable.
  2. Wire: 3.3 V → VCC, GND → GND, SDA → GPIO21, SCL → GPIO22 for both modules (they share the bus).
  3. Scan: run the I²C scanner and confirm 0x76 and 0x3C show up.
  4. Read and display: print temperature, humidity and pressure on the OLED and serial.
  5. Publish: send readings over MQTT every minute, sleep between samples.
  6. Harden: watchdog, reconnect logic, brown-out handling, and a weatherproof enclosure.
$ pio device list                         # is the board even detected? (cable might be power-only!)
$ pio device monitor -b 115200 --filter esp32_exception_decoder   # decode crash backtraces
$ sigrok-cli --driver fx2lafw --samples 1M --config samplerate=1m -C D0,D1 -o cap.sr    # cheap logic analyzer capture
tools to own
multimeter · soldering iron · logic analyzer (~$10) · bench supply or USB power meter · flush cutters
practise
Arduino project hub · Adafruit Learn · "Practical Electronics for Inventors" · Ben Eater's videos · nand2tetris
next steps
KiCad PCB design · STM32 and FreeRTOS · Rust embedded · BLE · CAN bus · sensor fusion
Say it like a pro

"Power, wiring, multimeter, serial, then logic analyzer, and I changed one thing at a time."