Nine spreads: electricity basics, components, microcontrollers, Arduino and ESP32 programming, sensors, communication buses, timing and interrupts, Raspberry Pi, and building a real project.
"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.
V = I × RP = V × I; resistors have wattage limits (¼ W typical)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
"I sized the series resistor with Ohm's law, and checked the rail with a multimeter before powering the MCU."
| Part | Use | Typical value |
|---|---|---|
| resistor | current limit, pull-up, divider | 220 Ω · 10 kΩ |
| electrolytic cap | smooth power rails | 100–470 µF |
| ceramic cap | decoupling | 0.1 µF |
| 1N4007 / 1N4148 | protection / signal diode | — |
| 2N2222 / IRLZ44N | NPN transistor / logic-level MOSFET | — |
| AMS1117-3.3 | 5 V → 3.3 V regulator | ≤ 800 mA |
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]
"A logic-level MOSFET switches the motor, a flyback diode protects it, and the grounds are shared."
// 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)
"I prototype on an ESP32 with PlatformIO, and move to MicroPython only when speed isn't critical."
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);
}
delay() so the loop stays responsive"Pull-ups with software debounce, a non-blocking loop built on millis(), and PWM for brightness."
#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); }
| Sensor | Measures | Bus |
|---|---|---|
| BME280 | temp, humidity, pressure | I²C / SPI |
| MPU6050 | acceleration, gyro | I²C |
| HC-SR04 | distance (ultrasonic) | GPIO pulse |
| NEO-6M | GPS position | UART |
| DHT22 | temp, humidity | one-wire style |
"I scanned the I²C bus to confirm the address, then checked pull-ups and voltage levels before blaming the library."
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); }
}
Serial.print, no delay.millis() wraps (~49 days on 32-bit); write now - then >= interval, which handles it."Short interrupt handlers that set flags, non-blocking timing with millis(), a watchdog enabled, and a state machine for behaviour."
#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() {}
| Source | Notes |
|---|---|
| USB 5 V | 500 mA typical; easy for development |
| Li-ion / LiPo 3.7 V | needs a charger and protection circuit; never short or puncture |
| 2×AA / AAA | simple, low drain; voltage sags as it drains |
| solar + supercap/LiPo | for outdoor sensors; add a charge controller |
"Deep sleep between samples, radio only briefly, an efficient regulator, and current measured, not guessed."
// 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
"MQTT with TLS and per-device credentials, devices on an isolated VLAN, and signed OTA updates."
$ 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
"Power, wiring, multimeter, serial, then logic analyzer, and I changed one thing at a time."