Projects · 08
Morse spy beacon
Type a secret message on your computer and the beacon flashes and beeps it in real Morse code. Tap the button to become the radio operator, then hold it for 3 seconds and the beacon repeats a message on its own, even on batteries. The wiring is the same as lesson K2, so this is the quickest first code project. Then, if you like, send Morse by radio between two boards, read it with a light sensor, or solder it into a small box.
Do these lessons first
- An LED and its resistor (E3)availablewhy the 220 Ω resistor, how a voltage is measured.
- Connect and upload code to your ESP32 (K1)availableinstall the board package, upload a sketch, open the Serial Monitor.
- Inputs, outputs and if (K2)availableread a button, switch an LED and a buzzer, make a decision. This mission uses exactly the K2 wiring.
You can start without them: the “Reminder” boxes give the idea in two lines. If you already built lesson K2 (or mission 01), your breadboard is ready: skip to step 8.
- Level
- Level 1an easy first code project: no soldering, same wiring as lesson K2
- Time
- One afternoon1–2 h (base build). Each “Go further” adds 1–2 h. Permanent version: add 2–3 h · estimate
- Cost
- —
- Tools
- Easybase build: no soldering, no power tools. The permanent version needs a soldering iron.
- Ask for help
- 1 stepstep 15
- Lesson first
- LEDs and the right resistoravailable
Low voltage only. USB (5 V) or a 4×AA pack, nothing else. No mains, and no laser: a bright LED is the light of this mission, and you never add a laser module to it.
Safety first
Read this box before you plug anything in.
- Batteries
- Small parts
- Low voltage only. USB (5 V) or a 4×AA pack, nothing else. No mains, and no laser: a bright LED is the light of this mission, and you never add a laser module to it.
- 3.3 V logic only. The ESP32 works at 3.3 V (3.6 V absolute maximum): never connect any ESP32 signal pin to 5 V. The one exception is the board's own
5Vpower pin, which takes the battery pack and nothing else. - The red rail is 3V3 only. The 4×AA pack goes into the
5Vpin row and the blue rail (−). Never put its + wire on a red rail. - Pack OFF before USB. The board takes one power source at a time. With the pack ON and USB plugged in, current can flow back into the cells. Switch the pack OFF before you plug in the USB cable, and before you move any wire.
- Batteries: never mix alkaline and rechargeable cells, old and new, or brands in one holder; replace all the cells at once. Follow the + / − marks inside the holder. Never let the bare ends of a pack touch each other or metal. Never recharge alkaline cells; recharge NiMH cells only in a NiMH charger, outside the box. No 9 V battery, no 5- or 6-cell holder, no LiPo for this mission. Take the cells out if the beacon sits unused for a month; white crust on a cell means it leaked, so wear gloves, clean it and dispose of it properly. Recycle used cells at a drop-off point.
- Do not send SOS where it could look real. No SOS (or any distress signal) flashed out of a window at night, near water or a road, or on a real radio. It is a game signal: for tests, use words like HELLO or OK.
- Flashing light: at the default speed the LED blinks a few times a second. If anyone nearby is sensitive to flashing lights (for example photosensitive epilepsy), do not use the LED near them. Keep it out of anyone's direct line of sight if they ask you to, and stay at the default speed.
- Buzzer: keep it short in shared spaces (the command
/quietswitches it off, the LED keeps working). Never hold the buzzer near your ear. - Radio option: the board uses its normal 2.4 GHz Wi-Fi radio, like any ESP32. Do not modify its antenna or boost its power. Real ham-radio frequencies are a different hobby and need a licence: they are not part of this mission.
- Light-sensor option: the light sensor (an LDR) contains cadmium sulfide. Do not break or burn it, and dispose of it as electronic waste.
- Small parts and cells: keep small parts, wires and batteries away from pets and from anyone who might put them in their mouth.
Parts
One list for everything, on a solder-free breadboard. The base build needs the first nine lines. The lines marked “Go further” are only for the options. Parts for the permanent version are in a separate list further down.
Show the 14 parts · —
- 1
ESP32 board×1
The brain
Exact spec: ESP32-DevKitC V4 or a clone: ESP32-WROOM-32, 38 pins, 3.3 V logic. Check the regulator before you run it on 4 alkaline cells (step 2): the 3-legged chip with a big tab near the
5Vpin should say AMS1117. - 2
Breadboard×1
Connects parts without soldering
Exact spec: Full-size 830 points. A 38-pin board plus its parts will not fit on a 400-point board.
- 3
Yellow LED, 5 mm×1
Flashes the dots and dashes
Exact spec: 5 mm, any “bright” yellow. Forward voltage about 2.0–2.2 V (typical, check on your LED's datasheet). Yellow is easy to see and different from mission 01's red, but any colour works with the same resistor.
- 4
220 Ω resistor×1
Protects the LED
Exact spec: 220 Ω, 1/4 W, through-hole. About (3.3 − 2.1) / 220 ≈ 5.5 mA: bright enough indoors and far below the usual 20 mA LED rating.
- 5
Active buzzer module×1
Beeps the dots and dashes
Exact spec: Active (built-in tone) module, 3 pins S / + / −, 3.3–5 V, sounds when S is HIGH. Some modules are the other way round: you test it in step 9 and can fix it in step 10. Takes roughly 20–30 mA (typical, to confirm on your module).
- 6
Push button×1
Your telegraph key
Exact spec: 6 mm tactile switch, 4 legs. No resistor needed: the code turns on the board's internal pull-up.
- 7
Jumper wiresabout 10
Link the parts
Exact spec: Male-to-male, about 10–20 cm.
- 8
USB data cable×1
Upload the code and type your messages
Exact spec: Data cable (not charge-only) matching the board's port.
- 9
4×AA battery holder with ON/OFF switch, cover and header-pin ends×1optional
Optional: runs the beacon away from the computer
Exact spec: Same holder as mission 01 (Adafruit 830 type). Fresh alkaline cells give about 6.4 V, flat ones about 4 V. The board needs about 4.4–6.5 V, so change the cells before they get that low. A 3×AA holder is not enough: it starts at 4.5 V and drops below the limit almost at once.
- 10
AA batteries×4optional
Optional: fill the 4×AA holder
Exact spec: Alkaline AA (LR6), or low-self-discharge NiMH AA. Same type and brand, never mixed. 4×NiMH only if your regulator is not an AMS1117 (step 2).
- 11
Second complete base kit (board, breadboard, LED, 220 Ω, buzzer, button, wires, USB cable)1 setoptional
Go further 1: the other end of the radio link
Exact spec: Identical to the base build. A friend's board works, as long as it is a 38-pin ESP32 with the same wiring.
- 12
Light-dependent resistor (LDR), GL5528 type×1optional
Go further 2: sees the other board's flashes
Exact spec: GL5528 or similar. A little slow (tens of milliseconds, typical, check the datasheet), which is why this option stays at 10 WPM or less. Contains cadmium sulfide (see Safety).
- 13
10 kΩ resistor×1optional
Go further 2: pairs with the LDR
Exact spec: 10 kΩ, 1/4 W, through-hole
- 14
Short opaque tube, 3–5 cm×1optional
Go further 2: shades the LDR so only the LED's light reaches it
Exact spec: A drinking straw wrapped in black tape, a roll of black paper, or a printed tube.
Tools
Show the 3 tools (2 optional)
Computer with Arduino IDE
Upload the code and read the Serial Monitor
Exact spec: Arduino IDE 2.x + “esp32 by Espressif” 3.3.x (free download from arduino.cc)
Sticky label and a penoptional
Label the battery pack (only if you use one)
Exact spec: Any
Multimeteroptional
Check cells and the pack voltage; measure the real battery life (needed for the permanent version)
Exact spec: Any basic digital multimeter
How it works
Type a message on your computer and the beacon flashes it with a yellow LED and beeps it with a buzzer, in real International Morse code. The board also writes the dots and dashes on the screen, so you can read what it sends.
The same button turns you into the radio operator. Press it and the LED and buzzer follow your finger; the board prints the letters you tap, so you see your mistakes at once. Hold the button for 3 seconds and the board becomes a lighthouse: it repeats a message every few seconds on its own, even on batteries, far from the computer. The message is the last one you typed, or HELLO AGENT after every power-on, reset or wake-up (so always HELLO AGENT on batteries, unless you change it in the code).
The wiring is exactly the one of lesson K2 (button on GPIO27, LED on GPIO26, buzzer on GPIO25), so if you did K2 or mission 01 there is nothing new to wire: only new code. That makes this the cheapest first code project, and you can read all of it. The options then add radio between two boards (ESP-NOW, no router) and a light sensor that reads the flashes, and a solder-and-box version makes the beacon permanent.
Related lessons: LEDs and the right resistor · Your first program: connect and upload code to your ESP32 · Inputs, outputs and if
Wiring
Two views of the same circuit: the breadboard as you will build it, and the schematic. Tap a diagram to open it full screen.
Show the 11 wires and the pin table
Wire list
| # | Colour | From | To |
|---|---|---|---|
| 1 | red | ESP32 3V3 (hole j19) | 3V3 rail (right red +) |
| 2 | black | ESP32 GND (hole j6) | GND rail (right blue −) |
| 3 | black | left blue rail | right blue rail (a link of GND) |
| 4 | orange | ESP32 GPIO25 (j11) | buzzer S (j39) |
| 5 | red | 3V3 rail | buzzer + (j40) |
| 6 | black | buzzer − (j41) | GND rail |
| 7 | green | ESP32 GPIO26 (j10) | b26 (row 26). The 220 Ω resistor then goes from d26 to d30, in the same row as this wire's end, so no two legs share a hole. The LED's long leg (+) goes in b30, in the row of the resistor's other end, and its short leg (−) in b31. |
| 8 | black | LED row 31 (a31, the short leg's row) | left blue rail |
| 9 | blue | ESP32 GPIO27 (j9) | button leg A (j44). The button straddles the middle gap, legs in e44, f44, e46, f46. |
| 10 | black | button leg B, diagonal from A (a46) | left blue rail |
| B | red / black | 4×AA pack (optional) | red + into the hole next to the 5V pin (j1), black − into the right blue rail. Never a red rail. Pack OFF until step 15. |
Hole names (j19, j6…) assume the board's pins sit in columns a and i of the breadboard, USB end at row 1 (step 3). These are exactly the holes of lesson K2 and mission 01 (minus the receiver), so a breadboard from either already runs this mission. The red rail on the right is 3V3 only; the left red rail stays unused.
ESP32 pins
| Pin | Goes to | Role |
|---|---|---|
5V | 4×AA pack + (battery use only, and the only thing that goes here) | Power in (about 4.4–6.5 V; below that it misbehaves) |
3V3 | 3V3 rail: buzzer + | Power out (3.3 V) |
GND | GND rail: pack −, buzzer −, LED, button | Ground |
GPIO27 | Button (other leg to GND) | Input with internal pull-up (LOW = pressed). Can wake the board from deep sleep. |
GPIO26 | 220 Ω → LED | Output (HIGH = LED on) |
GPIO25 | Buzzer S | Output (HIGH = buzzer on, unless your module is inverted) |
GPIO34 | Go further 2 only, on the receiver board: the middle of the LDR / 10 kΩ pair | Analog input (input-only pin) |
Pin order can differ on clones: always follow the labels printed on your board. The table above is for the original DevKitC V4. Avoid pins 0, 2, 5, 12 and 15 for your own add-ons: the board reads them at start-up.
Build steps
Do one step, check it, then go on.
Step 1 · Lay out your parts.
Base build only: board, breadboard, LED, 220 Ω resistor, buzzer, button, jumper wires, USB cable.
Check: Every part you need is on the table.
Step 2 · Check your board.
Look at the little 3-legged chip with a big flat tab, next to the
5Vpin. Read what is printed on it. If it says AMS1117 (the original board uses it), 4 alkaline cells are fine. If it is tiny, has 5 legs or has no marking, use 4 NiMH cells only. (You only need this if you will use the battery pack, but check now while the board is in your hand.) Also read the labels printed on the board next to the pins: on clones the order can differ from this sheet, and your labels win.Check: You know which chip regulates your board, and you have found the pins
5V,GND,3V3,25,26and27by their printed labels.Step 3 · Place the ESP32.
Press the board across the middle gap, so its two rows of pins land in columns a and i, rows 1 to 19. USB port at row 1, antenna toward row 20. Leave rows 20–23 empty: that is where the antenna sits. Each pin on the j side now has a free hole next to it (column j). No cable yet.
Check: The board sits flat, no pin is bent, and the pin
5Vis in row 1, column i.Step 4 · Rails.
Wire the ESP32 pin
3V3(hole j19) to the right red (+) rail and the pinGND(hole j6) to the right blue (−) rail. Then link the left blue rail to the right blue rail with one wire. The right red rail is now 3V3 only.Check: Red wire on the red rail, black wire on the blue rail, and nothing else touches the red rail yet.
Step 6 · Add the LED.
GPIO26→ 220 Ω resistor → long leg (+) of the LED. The green wire fromGPIO26ends in b26. The resistor goes from d26 to d30, so it shares row 26 with the wire but no hole. The LED's long leg goes in b30 (same row as the resistor's other end) and its short leg in b31. A wire runs from a31 to the left blue rail.Check: The long leg faces the resistor side.
Step 7 · Add the button.
Place the button across the middle gap, legs in e44, f44, e46 and f46. A wire from
GPIO27goes to one leg (j44 side) and a wire from the diagonally opposite leg (a46) goes to the left blue rail. No resistor needed: the code turns on the board's internal pull-up.Check: The two wired legs are diagonal from each other (not on the same side).
Step 8 · Upload the code.
Open the sketch “08-morse-beacon” in the Arduino IDE. Plug in the USB cable, choose “ESP32 Dev Module” and the right port, upload. Leave the cable plugged in. (No battery pack yet: one power source at a time.)
Check: “Done uploading” appears.
Step 9 · Say OK.
Open the Serial Monitor at 115200 baud and set the line ending to “Newline”. Press EN (reset). The LED and buzzer play OK in Morse (dash-dash-dash, dash-dot-dash), then the monitor prints a short help text. That is the board testing itself.
Check: You see and hear OK, and the help text appears. A buzzer that stays silent, or sounds the whole time and goes quiet on the beeps, works the other way round: go to step 10.
Step 10 · Fix a reversed buzzer (only if needed).
If the buzzer sounds when it should be silent, find
const int BUZZER_ON = HIGH;near the top of the code, changeHIGHtoLOW, upload again.Check: The buzzer is silent between signals and sounds with the LED.
Step 11 · Send your first message.
In the Serial Monitor, type
HELLOand press Enter. The monitor shows it in dots and dashes, then the LED and buzzer play it. Try your name. Capital or small letters, it does not matter. é is sent as ..-.. (ITU); other accented letters are skipped, and the monitor tells you. The line you typed is now the beacon's message, until the board is switched off, reset or goes to sleep (it then goes back to HELLO AGENT).Check: The dots and dashes on the monitor match the flashes. Keep tests to words like HELLO: never SOS (see Safety).
Step 12 · Tap with the key.
Press the button: the LED and buzzer follow your finger. Release: they stop. The board measures how long you pressed (short = dot, long = dash) and how long you waited, and prints what you tapped. Wait a moment after a letter and it appears on the monitor. Wait longer and it adds a space. Tap slowly: the board expects about 8 WPM. Try E (one dot), T (one dash), then the word HI (four dots, a pause, two dots).
Check: The monitor shows the dots and dashes as you tap them, then the letter. A wrong letter means a dot was too long or a gap too short: slow down.
Step 13 · Start the beacon.
Hold the button for 3 seconds. LED and buzzer give one short confirmation beep, then the beacon plays its message (your last typed line, or HELLO AGENT if you typed nothing since power-on), waits 5 seconds and plays it again, over and over, like a lighthouse. One tap on the button stops it. While it is sending, a press stops the message within one signal.
Check: After the 3 s hold, the message repeats every 5 s until you tap the button.
Step 14 · Change speed and volume.
Type
/wpm 15to send faster (allowed range 5–20 WPM). Type/quietto silence the buzzer (the LED keeps going) and/loudto bring it back./helplists the commands. Try different words at different speeds: where does it become hard to read by eye?Check: Messages play at the new speed and the buzzer obeys
/quiet.Step 15 · Run it on batteries (optional). Ask for help
USB unplugged first. Put 4 cells in the 4×AA holder, matching the + / − marks, switch it OFF and label it “ESP32 4×AA”. Plug its black pin end into the right blue (−) rail and its red pin end into the hole next to the
5Vpin (j1). Never into a red rail. Switch it ON: the board says OK. Hold the button 3 s to start the beacon, and tap to stop it. Without the computer you cannot type a message, and a typed message is forgotten when the power is cut, so on batteries the beacon always plays the default message of the code (HELLO AGENT). To send your own on batteries, changeDEFAULT_MESSAGEin the code and upload it again (pack OFF, then USB). Switch the pack OFF when you stop.Check: Red goes to the
5Vrow, black to the blue rail, and someone experienced (or you, twice) has checked it. The beacon runs without a cable.
What the board tells you (deep sleep, in plain words)
To make the batteries last, the board runs at a lower speed (80 MHz), keeps Wi-Fi and Bluetooth off, and goes to deep sleep after 3 minutes with nothing happening: nearly switched off, drawing very little. Pressing the button wakes it and it starts normally, with its OK. The one thing that never sleeps by itself is the beacon: that is its job, and it drains the pack (see below).
Show the 5 LED signals and the battery life
| What you see | What it means |
|---|---|
| OK in Morse at power-on | Self-test: the board started, and the LED and buzzer work. |
| LED and buzzer follow your finger | Straight-key mode: you are the operator. |
| One short beep after a 3 s hold | The beacon is starting. Let go of the button. |
| Your message every 5 s | Beacon running. One tap on the button stops it. |
| Two blinks, then dark | 3 minutes of nothing: the board is going to deep sleep. Press the button to wake it. |
Pressing the button to wake the board does not send a letter: it just restarts the program. On USB the sleep only saves the board; on batteries it saves the cells. You can turn it off in the code (SLEEP_AFTER_MS = 0). A message you typed is forgotten too: after a wake-up the beacon plays HELLO AGENT again.
How long do the batteries last?
| Pack | Battery life | Notes |
|---|---|---|
| Awake and waiting, 4×AA alkaline | about 2–3 days of continuous on-time | Roughly 30–40 mA, most of it the board's own chip, regulator and power LED. |
| Beacon running, 4×AA alkaline | about 1.5–2.5 days | The LED and the buzzer add to the board's own drain, mostly when the buzzer is on. /quiet saves some. |
| Deep sleep (after 3 min), 4×AA alkaline | about 10–12 days on standby | Almost all of the drain comes from the board's regulator and power LED, not from your code. |
| Radio option (Go further 1), listening, 4×AA alkaline | about 15–20 hours | The Wi-Fi radio listening costs the most: roughly 105–115 mA. Short bursts when sending cost more. |
Switch the pack OFF when you stop playing. Left on in beacon mode, it lasts about two days.
These are estimates from datasheet figures and typical values, not measurements. To measure on your build: put a multimeter in series with the pack's red wire and read the current in each state. When the cells run low the board becomes less reliable before it stops, so change all the cells together as soon as it misbehaves.
Code walkthrough
Board: ESP32 Dev Module (ESP32-DevKitC V4 or clone, ESP32-WROOM-32, 38 pins). The code below compiles in our CI with the ESP32 board package 3.3.12.
Nothing to install for the base sketch. Three sketches: the base one (08-morse-beacon, no Wi-Fi), the radio one (08b-morse-radio, Go further 1) and the light one (08c-morse-light, Go further 2). The base sketch has no libraries and is written to be read: short and full of comments.
Download the .ino file Download the sketch folder (.zip)
Chunk 1 Header and wiring
Notes at the top: what the sketch does (typed messages, the button as a key, beacon mode), the commands, the wiring (the same as lesson K2) and the battery rule. Then three includes used for deep sleep: the RTC pins, whose pull-up keeps working while the board sleeps, the pin hold that keeps the LED and buzzer off, and the sleep functions. What to change: nothing
Show the code (27 lines)
// Tinker Mission — Mission 08: Morse spy beacon // Board: ESP32 Dev Module ("esp32 by Espressif" 3.3.x). No extra library needed. // // How it works: // 1. Type a message in the Serial Monitor (115200 baud, "Newline"): the LED flashes it and the // buzzer beeps it in real International Morse code. It also becomes the beacon message. // 2. Press the button like a radio operator's key: the LED and buzzer follow your finger, and // the Serial Monitor shows the dots, dashes and letters you tapped. // 3. Hold the button 3 s: beacon mode. The message repeats every 5 s until you tap the button. // It repeats your last typed message, or DEFAULT_MESSAGE if you typed nothing since power-on // (always the case on batteries, away from the computer). // Nothing happens for 3 minutes (and no beacon)? The board goes to deep sleep. Press the button // to wake it up. // // Commands you can type: /wpm 15 (speed, 5 to 20 words per minute), /quiet (buzzer off), // /loud (buzzer on), /help. // // Wiring (ESP32 DevKitC, 38 pins), the same as lesson K2: // Push button GPIO27 -> button -> GND // LED GPIO26 -> 220 ohm resistor -> LED long leg; LED short leg -> GND // Buzzer module S -> GPIO25 + -> 3V3 - -> GND (active buzzer) // 4xAA pack (optional) red (+) -> 5V pin black (-) -> GND (5V pin ONLY, never a red rail) // Switch the pack OFF before you plug in the USB cable: one power source at a time. #include "driver/rtc_io.h" // "RTC" pins: their pull-ups keep working while the ESP32 sleeps #include "driver/gpio.h" // gpio_hold_en(): freezes an output pin at its level during sleep #include "esp_sleep.h" // deep sleep and wake-up sourcesChunk 2 Pins, settings and default message
A name for each pin (
LED_PIN,BUZZER_PIN,BUTTON_PIN), which level makes the buzzer sound (BUZZER_ON), then the numbers you may change: send speed (10 WPM), key speed (8 WPM), hold time for the beacon (3 s), pause between beacon messages (5 s), time before deep sleep (3 min), longest message (100 characters) and the limits the button decoder uses.DEFAULT_MESSAGE(“HELLO AGENT”) is what the beacon plays after every power-on, reset or wake-up. What to change:BUZZER_ONonly if step 10 told you to;DEFAULT_MESSAGEfor your own beacon text; the numbers if you likeShow the code (25 lines)
// ---------- Pins ---------- const gpio_num_t BUTTON_PIN = GPIO_NUM_27; // pressed = LOW (wired to GND). Can wake the ESP32. const gpio_num_t LED_PIN = GPIO_NUM_26; const gpio_num_t BUZZER_PIN = GPIO_NUM_25; // ---------- Settings you may change ---------- // Most buzzer modules beep when S is HIGH. A "low-level trigger" module beeps when S is LOW: // if yours beeps all the time, change HIGH to LOW. const int BUZZER_ON = HIGH; const int SEND_WPM = 10; // sending speed at start-up, in words per minute const int KEY_WPM = 8; // how fast we expect YOU to tap the button const unsigned long HOLD_FOR_BEACON_MS = 3000; // hold the button this long = beacon mode const unsigned long BEACON_PAUSE_MS = 5000; // beacon: pause between two repeats const unsigned long SLEEP_AFTER_MS = 180000; // 3 minutes without activity = deep sleep (0 = never) // The beacon message after power-on. On batteries (no computer, so nothing typed) the beacon // always plays this one: change it here, then upload again. A typed message replaces it only // until the board is switched off, reset or goes to deep sleep (it lives in normal memory). const char* DEFAULT_MESSAGE = "HELLO AGENT"; const int MAX_LINE = 100; // longest message, in characters // How the button decoder tells things apart, counted in "units" (one unit = one dot): const float DASH_AT_UNITS = 2.0; // a press shorter than 2 units is a dot, longer is a dash const float LETTER_END_UNITS = 2.5; // silence of 2.5 units = the letter is finished const float WORD_END_UNITS = 6.0; // silence of 6 units = the word is finished const unsigned long DEBOUNCE_MS = 30; // a button "bounces" for a few ms: ignore changes this shortChunk 3 The Morse table and timing
The alphabet, digits and punctuation, each written as dots and dashes in a plain list (ITU-R M.1677-1). Then the timing rules (dash = 3 units, gaps of 1, 3 and 7) and the unit, 1200 ÷ WPM milliseconds. Three small functions:
morseFor()finds the dots and dashes of a character (small letters become capitals, é is sent as ..-.., other unknown characters give nothing),letterFor()goes the other way,morseUnits()counts how long a message lasts. What to change: nothingShow the code (67 lines)
// ---------- Morse code table and timing (pure code: no pins, no Serial) ---------- // International Morse code (ITU-R M.1677-1): letters, figures, some punctuation and É. const char* MORSE[][2] = { {"A", ".-"}, {"B", "-..."}, {"C", "-.-."}, {"D", "-.."}, {"E", "."}, {"F", "..-."}, {"G", "--."}, {"H", "...."}, {"I", ".."}, {"J", ".---"}, {"K", "-.-"}, {"L", ".-.."}, {"M", "--"}, {"N", "-."}, {"O", "---"}, {"P", ".--."}, {"Q", "--.-"}, {"R", ".-."}, {"S", "..."}, {"T", "-"}, {"U", "..-"}, {"V", "...-"}, {"W", ".--"}, {"X", "-..-"}, {"Y", "-.--"}, {"Z", "--.."}, {"0", "-----"}, {"1", ".----"}, {"2", "..---"}, {"3", "...--"}, {"4", "....-"}, {"5", "....."}, {"6", "-...."}, {"7", "--..."}, {"8", "---.."}, {"9", "----."}, {".", ".-.-.-"}, {",", "--..--"}, {"?", "..--.."}, {"'", ".----."}, {"/", "-..-."}, {"(", "-.--."}, {")", "-.--.-"}, {":", "---..."}, {"=", "-...-"}, {"+", ".-.-."}, {"-", "-....-"}, {"\"", ".-..-."}, {"@", ".--.-."}, {"É", "..-.."}, // the only accented letter in the ITU table (é is sent as É) }; const int MORSE_COUNT = sizeof(MORSE) / sizeof(MORSE[0]); // Morse timing, in units: a dash is 3 dots long. Silences: 1 unit inside a letter, // 3 units between letters, 7 units between words. const int DOT = 1, DASH = 3, ELEMENT_GAP = 1, LETTER_GAP = 3, WORD_GAP = 7; // One unit in milliseconds. The word "PARIS" (with its word gap) is exactly 50 units, and // "10 words per minute" means 10 PARIS per minute: 60000 ms / (50 x WPM) = 1200 / WPM. unsigned long unitMs(int wpm) { return 1200 / wpm; } // How many bytes the character at the start of text takes. The Serial Monitor sends text as // UTF-8: 1 byte for A-Z, figures, punctuation and spaces; 2 for é (0xC3 0xA9); up to 4 for emoji. int charBytes(const char* text) { int n = 1; if ((unsigned char)text[0] >= 0xC0) // first byte of a longer character... while ((text[n] & 0xC0) == 0x80) n++; // ...its next bytes all start with the bits 10 return n; } // The dots and dashes of the character at the start of text, or NULL if it has no Morse code // (other accented letters, emoji...). Lowercase letters count as uppercase, and é as É. const char* morseFor(const char* text) { int n = charBytes(text); if (n > 2) return NULL; char key[3] = {(char)toupper((unsigned char)text[0]), n == 2 ? text[1] : (char)0, 0}; if (strcmp(key, "é") == 0) strcpy(key, "É"); for (int i = 0; i < MORSE_COUNT; i++) if (strcmp(MORSE[i][0], key) == 0) return MORSE[i][1]; return NULL; } // The character for some dots and dashes ("É" is 2 bytes), or "?" if no character has them. const char* letterFor(const char* code) { for (int i = 0; i < MORSE_COUNT; i++) if (strcmp(MORSE[i][1], code) == 0) return MORSE[i][0]; return "?"; } // How long a message lasts, in units, with exactly the rules sendMorse() uses below // (characters with no Morse code skipped, several spaces = one word gap, a word gap at the end). int morseUnits(const char* text) { int units = 0, gapBefore = 0; // gapBefore = silence to leave before the next letter for (int i = 0; text[i] != 0; i += charBytes(text + i)) { if (text[i] == ' ') { if (gapBefore > 0) gapBefore = WORD_GAP; continue; } const char* code = morseFor(text + i); if (code == NULL) continue; units += gapBefore; for (int k = 0; code[k] != 0; k++) units += (k > 0 ? ELEMENT_GAP : 0) + (code[k] == '.' ? DOT : DASH); gapBefore = LETTER_GAP; } return gapBefore > 0 ? units + WORD_GAP : 0; }Chunk 4 Memory and small helpers
The variables that remember what the board is doing: speed, quiet or not, the beacon message (it starts as
DEFAULT_MESSAGE) and the button decoder. Then the helpers:setSignal()switches the LED and the buzzer together (the buzzer stays silent after/quiet),waitOrPress()waits but stops at once if the button is pressed, andprintHelp(). What to change: nothingShow the code (46 lines)
// ---------- Variables ---------- int sendWpm = SEND_WPM; // changed with /wpm bool quiet = false; // /quiet: buzzer off, the LED still works String beaconMessage = DEFAULT_MESSAGE; bool beaconOn = false; unsigned long nextBeaconAt = 0; // when the beacon plays the message again unsigned long lastActivity = 0; // for the deep sleep timer // Button decoder bool keyDown = false; // the button, after debouncing bool lastRaw = false; // the button, as read just now unsigned long lastChange = 0; // when the raw reading last changed unsigned long pressStart = 0, releasedAt = 0; bool ignorePress = false; // this press stops the beacon: do not decode it String tapped = ""; // dots and dashes of the letter being tapped String tappedWord = ""; // letters of the word being tapped // ---------- Small helpers ---------- // LED and buzzer together (the buzzer only if not /quiet). void setSignal(bool on) { digitalWrite(LED_PIN, on ? HIGH : LOW); digitalWrite(BUZZER_PIN, (on && !quiet) ? BUZZER_ON : !BUZZER_ON); } bool buttonPressed() { return digitalRead(BUTTON_PIN) == LOW; } void waitButtonRelease() { while (buttonPressed()) delay(10); delay(50); // ignore button bounce } // Waits `ms` milliseconds, but stops early and returns true if the button is pressed. bool waitOrPress(unsigned long ms) { unsigned long start = millis(); while (millis() - start < ms) { if (buttonPressed()) return true; delay(1); } return false; } void printHelp() { Serial.println("Type a message and press Enter: I send it in Morse."); Serial.println("Commands: /wpm 15 (speed 5-20) /quiet /loud /help"); Serial.println("Button: tap Morse yourself. Hold 3 s = beacon mode, tap to stop it."); }Chunk 5 Sending a message
sendMorse()walks through the text letter by letter, plays each dot and dash, leaves the right gaps and checks the button between signals, so a press can stop it.printMorse()shows the dots and dashes with the duration and lists the characters it skipped.sendAndReport()puts the two together. What to change: nothingShow the code (49 lines)
// ---------- Sending Morse: LED + buzzer ---------- // Plays a text in Morse. Returns true if the button stopped it. bool sendMorse(const char* text) { unsigned long unit = unitMs(sendWpm); int gapBefore = 0; // silence to leave before the next letter (0 before the first one) for (int i = 0; text[i] != 0; i += charBytes(text + i)) { if (text[i] == ' ') { if (gapBefore > 0) gapBefore = WORD_GAP; continue; } const char* code = morseFor(text + i); if (code == NULL) continue; // no Morse code for it: skip if (waitOrPress(gapBefore * unit)) return true; for (int k = 0; code[k] != 0; k++) { if (k > 0 && waitOrPress(ELEMENT_GAP * unit)) return true; setSignal(true); bool pressed = waitOrPress((code[k] == '.' ? DOT : DASH) * unit); setSignal(false); if (pressed) return true; } gapBefore = LETTER_GAP; } return gapBefore > 0 && waitOrPress(WORD_GAP * unit); // word gap at the end } // Shows "SOS -> ... --- ..." on the Serial Monitor, and lists the characters with no Morse code. void printMorse(const char* text) { String skipped = ""; Serial.print(text); Serial.print(" ->"); for (int i = 0; text[i] != 0; i += charBytes(text + i)) { const char* code = morseFor(text + i); if (text[i] == ' ') Serial.print(" /"); else if (code == NULL) for (int k = 0; k < charBytes(text + i); k++) skipped += text[i + k]; else { Serial.print(" "); Serial.print(code); } } Serial.print(" ("); Serial.print(morseUnits(text) * unitMs(sendWpm) / 1000.0, 1); Serial.println(" s)"); if (skipped.length() > 0) { Serial.print("skipped: "); Serial.println(skipped); } } // Sends a text; if the button stops it, wait for the release so that press is not decoded. void sendAndReport(const char* text) { if (sendMorse(text)) { Serial.println("Stopped by the button."); waitButtonRelease(); keyDown = lastRaw = false; beaconOn = false; } lastActivity = millis(); }Chunk 6 Typed lines, commands and beacon mode
handleLine()cleans up the line you typed. A line starting with/is a command:/wpm(5 to 20),/quiet,/loud,/help. Any other line is a message: cut to 100 characters, shown in dots and dashes, played, and kept as the beacon message until power-off, reset or sleep.startBeacon()gives one short confirmation beep and starts the repeat;stopBeacon()ends it. What to change: the5and20of/wpm, if you want another speed rangeShow the code (49 lines)
// ---------- Typed lines and commands ---------- void handleLine(String line) { line.trim(); // removes spaces and line endings at both ends if (line.length() == 0) return; if (line.startsWith("/wpm")) { sendWpm = constrain(line.substring(4).toInt(), 5, 20); // keeps it between 5 and 20 Serial.print("Speed: "); Serial.print(sendWpm); Serial.println(" words per minute"); } else if (line == "/quiet") { quiet = true; Serial.println("Buzzer off (the LED still flashes)"); } else if (line == "/loud") { quiet = false; Serial.println("Buzzer on"); } else if (line.startsWith("/")) { printHelp(); } else { if (line.length() > MAX_LINE) { line = line.substring(0, MAX_LINE); Serial.println("Too long: only the first 100 characters are sent."); } beaconMessage = line; // the beacon repeats this one until power-off, reset or sleep printMorse(line.c_str()); sendAndReport(line.c_str()); } } // ---------- Beacon mode ---------- void startBeacon() { setSignal(false); tapped = ""; tappedWord = ""; ignorePress = true; // the long press itself is not a dash delay(200); setSignal(true); // one short beep = beacon mode on delay(100); setSignal(false); beaconOn = true; nextBeaconAt = millis() + 1000; Serial.print("Beacon mode: "); Serial.println(beaconMessage); } void stopBeacon() { beaconOn = false; ignorePress = true; // the stop press is not decoded Serial.println("Beacon stopped."); }Chunk 7 The button as a Morse key
readKey()ignores changes shorter than 30 ms (debounce), makes the LED and buzzer follow your finger and times each press: short = dot, long = dash. A silence of about 2.5 units ends a letter and 6 units ends a word. It looks the letter up in the table, or prints ? if nothing matches. A 3-second hold callsstartBeacon(); a press while the beacon runs stops it. What to change: the thresholds (see Pins), if you tap very fast or very slowlyShow the code (39 lines)
// ---------- The button as a Morse key ---------- void readKey() { unsigned long now = millis(); bool raw = buttonPressed(); if (raw != lastRaw) { lastRaw = raw; lastChange = now; } if (raw != keyDown && now - lastChange >= DEBOUNCE_MS) { // a real change keyDown = raw; lastActivity = now; if (keyDown) { // just pressed pressStart = now; if (beaconOn) stopBeacon(); else setSignal(true); // the LED and buzzer follow your finger } else { // just released setSignal(false); if (ignorePress) { ignorePress = false; return; } unsigned long unit = unitMs(KEY_WPM); char symbol = (now - pressStart < DASH_AT_UNITS * unit) ? '.' : '-'; tapped += symbol; Serial.print(symbol); // show each dot or dash at once releasedAt = now; } } unsigned long unit = unitMs(KEY_WPM); if (keyDown && !ignorePress && now - pressStart >= HOLD_FOR_BEACON_MS) startBeacon(); if (!keyDown && tapped.length() > 0 && now - releasedAt >= LETTER_END_UNITS * unit) { const char* letter = letterFor(tapped.c_str()); // "?" if the dots and dashes mean nothing Serial.print(" "); Serial.println(letter); tappedWord += letter; tapped = ""; } if (!keyDown && tappedWord.length() > 0 && now - releasedAt >= WORD_END_UNITS * unit) { Serial.print("Word: "); Serial.println(tappedWord); tappedWord = ""; } }Chunk 8 Deep sleep, start-up and loop
goToSleep()blinks twice, freezes the LED and buzzer off, keeps the button's pull-up alive and asks to be woken whenGPIO27goes LOW.setup()runs at power-on, reset and every wake-up: it slows the board to 80 MHz, plays OK and prints the help.loop()listens to the Serial Monitor and the button, plays the beacon when it is due, and sleeps after 3 idle minutes (never during the beacon or while the button is down). What to change:SLEEP_AFTER_MS(0 = never sleep)Show the code (59 lines)
// ---------- Deep sleep ---------- void goToSleep() { Serial.println("Nothing for 3 minutes: sleeping. Press the button to wake me up."); for (int i = 0; i < 2; i++) { // two blinks = going to sleep digitalWrite(LED_PIN, HIGH); delay(150); digitalWrite(LED_PIN, LOW); delay(150); } // Freeze the buzzer OFF and the LED off during sleep (else the pins could float). digitalWrite(BUZZER_PIN, !BUZZER_ON); gpio_hold_en(BUZZER_PIN); gpio_hold_en(LED_PIN); gpio_deep_sleep_hold_en(); // Keep the "RTC" part powered so the button's pull-up keeps working (a few microamps). esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON); rtc_gpio_init(BUTTON_PIN); rtc_gpio_set_direction(BUTTON_PIN, RTC_GPIO_MODE_INPUT_ONLY); rtc_gpio_pullup_en(BUTTON_PIN); rtc_gpio_pulldown_dis(BUTTON_PIN); esp_sleep_enable_ext0_wakeup(BUTTON_PIN, LOW); // wake up when the button pulls GPIO27 LOW Serial.flush(); esp_deep_sleep_start(); // the ESP32 stops here; waking up starts setup() again } // ---------- setup(): runs at power-on, reset and every wake-up ---------- void setup() { setCpuFrequencyMhz(80); // slower = less current. Wi-Fi and Bluetooth stay off. Serial.begin(115200); // Unfreeze the outputs, and give the button pin back to normal code. gpio_hold_dis(BUZZER_PIN); gpio_hold_dis(LED_PIN); rtc_gpio_deinit(BUTTON_PIN); pinMode(BUZZER_PIN, OUTPUT); pinMode(LED_PIN, OUTPUT); setSignal(false); pinMode(BUTTON_PIN, INPUT_PULLUP); // built-in pull-up: pressed = LOW if (esp_sleep_get_wakeup_cause() == ESP_SLEEP_WAKEUP_EXT0) waitButtonRelease(); // woken by the button Serial.println(); Serial.println("Morse spy beacon ready."); sendAndReport("OK"); // self-test: --- -.- on the LED and buzzer printHelp(); lastActivity = millis(); } // ---------- loop(): runs again and again ---------- void loop() { if (Serial.available()) { // a typed line (the Serial Monitor sends it when you press Enter) lastActivity = millis(); handleLine(Serial.readStringUntil('\n')); } readKey(); if (beaconOn && !keyDown && (long)(millis() - nextBeaconAt) >= 0) { sendAndReport(beaconMessage.c_str()); nextBeaconAt = millis() + BEACON_PAUSE_MS; } if (SLEEP_AFTER_MS > 0 && !beaconOn && !keyDown && millis() - lastActivity >= SLEEP_AFTER_MS) goToSleep(); }
The whole sketch, in one piece
// Tinker Mission — Mission 08: Morse spy beacon
// Board: ESP32 Dev Module ("esp32 by Espressif" 3.3.x). No extra library needed.
//
// How it works:
// 1. Type a message in the Serial Monitor (115200 baud, "Newline"): the LED flashes it and the
// buzzer beeps it in real International Morse code. It also becomes the beacon message.
// 2. Press the button like a radio operator's key: the LED and buzzer follow your finger, and
// the Serial Monitor shows the dots, dashes and letters you tapped.
// 3. Hold the button 3 s: beacon mode. The message repeats every 5 s until you tap the button.
// It repeats your last typed message, or DEFAULT_MESSAGE if you typed nothing since power-on
// (always the case on batteries, away from the computer).
// Nothing happens for 3 minutes (and no beacon)? The board goes to deep sleep. Press the button
// to wake it up.
//
// Commands you can type: /wpm 15 (speed, 5 to 20 words per minute), /quiet (buzzer off),
// /loud (buzzer on), /help.
//
// Wiring (ESP32 DevKitC, 38 pins), the same as lesson K2:
// Push button GPIO27 -> button -> GND
// LED GPIO26 -> 220 ohm resistor -> LED long leg; LED short leg -> GND
// Buzzer module S -> GPIO25 + -> 3V3 - -> GND (active buzzer)
// 4xAA pack (optional) red (+) -> 5V pin black (-) -> GND (5V pin ONLY, never a red rail)
// Switch the pack OFF before you plug in the USB cable: one power source at a time.
#include "driver/rtc_io.h" // "RTC" pins: their pull-ups keep working while the ESP32 sleeps
#include "driver/gpio.h" // gpio_hold_en(): freezes an output pin at its level during sleep
#include "esp_sleep.h" // deep sleep and wake-up sources
// ---------- Pins ----------
const gpio_num_t BUTTON_PIN = GPIO_NUM_27; // pressed = LOW (wired to GND). Can wake the ESP32.
const gpio_num_t LED_PIN = GPIO_NUM_26;
const gpio_num_t BUZZER_PIN = GPIO_NUM_25;
// ---------- Settings you may change ----------
// Most buzzer modules beep when S is HIGH. A "low-level trigger" module beeps when S is LOW:
// if yours beeps all the time, change HIGH to LOW.
const int BUZZER_ON = HIGH;
const int SEND_WPM = 10; // sending speed at start-up, in words per minute
const int KEY_WPM = 8; // how fast we expect YOU to tap the button
const unsigned long HOLD_FOR_BEACON_MS = 3000; // hold the button this long = beacon mode
const unsigned long BEACON_PAUSE_MS = 5000; // beacon: pause between two repeats
const unsigned long SLEEP_AFTER_MS = 180000; // 3 minutes without activity = deep sleep (0 = never)
// The beacon message after power-on. On batteries (no computer, so nothing typed) the beacon
// always plays this one: change it here, then upload again. A typed message replaces it only
// until the board is switched off, reset or goes to deep sleep (it lives in normal memory).
const char* DEFAULT_MESSAGE = "HELLO AGENT";
const int MAX_LINE = 100; // longest message, in characters
// How the button decoder tells things apart, counted in "units" (one unit = one dot):
const float DASH_AT_UNITS = 2.0; // a press shorter than 2 units is a dot, longer is a dash
const float LETTER_END_UNITS = 2.5; // silence of 2.5 units = the letter is finished
const float WORD_END_UNITS = 6.0; // silence of 6 units = the word is finished
const unsigned long DEBOUNCE_MS = 30; // a button "bounces" for a few ms: ignore changes this short
// ---------- Morse code table and timing (pure code: no pins, no Serial) ----------
// International Morse code (ITU-R M.1677-1): letters, figures, some punctuation and É.
const char* MORSE[][2] = {
{"A", ".-"}, {"B", "-..."}, {"C", "-.-."}, {"D", "-.."}, {"E", "."}, {"F", "..-."},
{"G", "--."}, {"H", "...."}, {"I", ".."}, {"J", ".---"}, {"K", "-.-"}, {"L", ".-.."},
{"M", "--"}, {"N", "-."}, {"O", "---"}, {"P", ".--."}, {"Q", "--.-"}, {"R", ".-."},
{"S", "..."}, {"T", "-"}, {"U", "..-"}, {"V", "...-"}, {"W", ".--"}, {"X", "-..-"},
{"Y", "-.--"}, {"Z", "--.."},
{"0", "-----"}, {"1", ".----"}, {"2", "..---"}, {"3", "...--"}, {"4", "....-"},
{"5", "....."}, {"6", "-...."}, {"7", "--..."}, {"8", "---.."}, {"9", "----."},
{".", ".-.-.-"}, {",", "--..--"}, {"?", "..--.."}, {"'", ".----."}, {"/", "-..-."},
{"(", "-.--."}, {")", "-.--.-"}, {":", "---..."}, {"=", "-...-"}, {"+", ".-.-."},
{"-", "-....-"}, {"\"", ".-..-."}, {"@", ".--.-."},
{"É", "..-.."}, // the only accented letter in the ITU table (é is sent as É)
};
const int MORSE_COUNT = sizeof(MORSE) / sizeof(MORSE[0]);
// Morse timing, in units: a dash is 3 dots long. Silences: 1 unit inside a letter,
// 3 units between letters, 7 units between words.
const int DOT = 1, DASH = 3, ELEMENT_GAP = 1, LETTER_GAP = 3, WORD_GAP = 7;
// One unit in milliseconds. The word "PARIS" (with its word gap) is exactly 50 units, and
// "10 words per minute" means 10 PARIS per minute: 60000 ms / (50 x WPM) = 1200 / WPM.
unsigned long unitMs(int wpm) { return 1200 / wpm; }
// How many bytes the character at the start of text takes. The Serial Monitor sends text as
// UTF-8: 1 byte for A-Z, figures, punctuation and spaces; 2 for é (0xC3 0xA9); up to 4 for emoji.
int charBytes(const char* text) {
int n = 1;
if ((unsigned char)text[0] >= 0xC0) // first byte of a longer character...
while ((text[n] & 0xC0) == 0x80) n++; // ...its next bytes all start with the bits 10
return n;
}
// The dots and dashes of the character at the start of text, or NULL if it has no Morse code
// (other accented letters, emoji...). Lowercase letters count as uppercase, and é as É.
const char* morseFor(const char* text) {
int n = charBytes(text);
if (n > 2) return NULL;
char key[3] = {(char)toupper((unsigned char)text[0]), n == 2 ? text[1] : (char)0, 0};
if (strcmp(key, "é") == 0) strcpy(key, "É");
for (int i = 0; i < MORSE_COUNT; i++)
if (strcmp(MORSE[i][0], key) == 0) return MORSE[i][1];
return NULL;
}
// The character for some dots and dashes ("É" is 2 bytes), or "?" if no character has them.
const char* letterFor(const char* code) {
for (int i = 0; i < MORSE_COUNT; i++)
if (strcmp(MORSE[i][1], code) == 0) return MORSE[i][0];
return "?";
}
// How long a message lasts, in units, with exactly the rules sendMorse() uses below
// (characters with no Morse code skipped, several spaces = one word gap, a word gap at the end).
int morseUnits(const char* text) {
int units = 0, gapBefore = 0; // gapBefore = silence to leave before the next letter
for (int i = 0; text[i] != 0; i += charBytes(text + i)) {
if (text[i] == ' ') { if (gapBefore > 0) gapBefore = WORD_GAP; continue; }
const char* code = morseFor(text + i);
if (code == NULL) continue;
units += gapBefore;
for (int k = 0; code[k] != 0; k++) units += (k > 0 ? ELEMENT_GAP : 0) + (code[k] == '.' ? DOT : DASH);
gapBefore = LETTER_GAP;
}
return gapBefore > 0 ? units + WORD_GAP : 0;
}
// ---------- Variables ----------
int sendWpm = SEND_WPM; // changed with /wpm
bool quiet = false; // /quiet: buzzer off, the LED still works
String beaconMessage = DEFAULT_MESSAGE;
bool beaconOn = false;
unsigned long nextBeaconAt = 0; // when the beacon plays the message again
unsigned long lastActivity = 0; // for the deep sleep timer
// Button decoder
bool keyDown = false; // the button, after debouncing
bool lastRaw = false; // the button, as read just now
unsigned long lastChange = 0; // when the raw reading last changed
unsigned long pressStart = 0, releasedAt = 0;
bool ignorePress = false; // this press stops the beacon: do not decode it
String tapped = ""; // dots and dashes of the letter being tapped
String tappedWord = ""; // letters of the word being tapped
// ---------- Small helpers ----------
// LED and buzzer together (the buzzer only if not /quiet).
void setSignal(bool on) {
digitalWrite(LED_PIN, on ? HIGH : LOW);
digitalWrite(BUZZER_PIN, (on && !quiet) ? BUZZER_ON : !BUZZER_ON);
}
bool buttonPressed() { return digitalRead(BUTTON_PIN) == LOW; }
void waitButtonRelease() {
while (buttonPressed()) delay(10);
delay(50); // ignore button bounce
}
// Waits `ms` milliseconds, but stops early and returns true if the button is pressed.
bool waitOrPress(unsigned long ms) {
unsigned long start = millis();
while (millis() - start < ms) {
if (buttonPressed()) return true;
delay(1);
}
return false;
}
void printHelp() {
Serial.println("Type a message and press Enter: I send it in Morse.");
Serial.println("Commands: /wpm 15 (speed 5-20) /quiet /loud /help");
Serial.println("Button: tap Morse yourself. Hold 3 s = beacon mode, tap to stop it.");
}
// ---------- Sending Morse: LED + buzzer ----------
// Plays a text in Morse. Returns true if the button stopped it.
bool sendMorse(const char* text) {
unsigned long unit = unitMs(sendWpm);
int gapBefore = 0; // silence to leave before the next letter (0 before the first one)
for (int i = 0; text[i] != 0; i += charBytes(text + i)) {
if (text[i] == ' ') { if (gapBefore > 0) gapBefore = WORD_GAP; continue; }
const char* code = morseFor(text + i);
if (code == NULL) continue; // no Morse code for it: skip
if (waitOrPress(gapBefore * unit)) return true;
for (int k = 0; code[k] != 0; k++) {
if (k > 0 && waitOrPress(ELEMENT_GAP * unit)) return true;
setSignal(true);
bool pressed = waitOrPress((code[k] == '.' ? DOT : DASH) * unit);
setSignal(false);
if (pressed) return true;
}
gapBefore = LETTER_GAP;
}
return gapBefore > 0 && waitOrPress(WORD_GAP * unit); // word gap at the end
}
// Shows "SOS -> ... --- ..." on the Serial Monitor, and lists the characters with no Morse code.
void printMorse(const char* text) {
String skipped = "";
Serial.print(text);
Serial.print(" ->");
for (int i = 0; text[i] != 0; i += charBytes(text + i)) {
const char* code = morseFor(text + i);
if (text[i] == ' ') Serial.print(" /");
else if (code == NULL) for (int k = 0; k < charBytes(text + i); k++) skipped += text[i + k];
else { Serial.print(" "); Serial.print(code); }
}
Serial.print(" (");
Serial.print(morseUnits(text) * unitMs(sendWpm) / 1000.0, 1);
Serial.println(" s)");
if (skipped.length() > 0) { Serial.print("skipped: "); Serial.println(skipped); }
}
// Sends a text; if the button stops it, wait for the release so that press is not decoded.
void sendAndReport(const char* text) {
if (sendMorse(text)) {
Serial.println("Stopped by the button.");
waitButtonRelease();
keyDown = lastRaw = false;
beaconOn = false;
}
lastActivity = millis();
}
// ---------- Typed lines and commands ----------
void handleLine(String line) {
line.trim(); // removes spaces and line endings at both ends
if (line.length() == 0) return;
if (line.startsWith("/wpm")) {
sendWpm = constrain(line.substring(4).toInt(), 5, 20); // keeps it between 5 and 20
Serial.print("Speed: ");
Serial.print(sendWpm);
Serial.println(" words per minute");
} else if (line == "/quiet") {
quiet = true;
Serial.println("Buzzer off (the LED still flashes)");
} else if (line == "/loud") {
quiet = false;
Serial.println("Buzzer on");
} else if (line.startsWith("/")) {
printHelp();
} else {
if (line.length() > MAX_LINE) {
line = line.substring(0, MAX_LINE);
Serial.println("Too long: only the first 100 characters are sent.");
}
beaconMessage = line; // the beacon repeats this one until power-off, reset or sleep
printMorse(line.c_str());
sendAndReport(line.c_str());
}
}
// ---------- Beacon mode ----------
void startBeacon() {
setSignal(false);
tapped = "";
tappedWord = "";
ignorePress = true; // the long press itself is not a dash
delay(200);
setSignal(true); // one short beep = beacon mode on
delay(100);
setSignal(false);
beaconOn = true;
nextBeaconAt = millis() + 1000;
Serial.print("Beacon mode: ");
Serial.println(beaconMessage);
}
void stopBeacon() {
beaconOn = false;
ignorePress = true; // the stop press is not decoded
Serial.println("Beacon stopped.");
}
// ---------- The button as a Morse key ----------
void readKey() {
unsigned long now = millis();
bool raw = buttonPressed();
if (raw != lastRaw) { lastRaw = raw; lastChange = now; }
if (raw != keyDown && now - lastChange >= DEBOUNCE_MS) { // a real change
keyDown = raw;
lastActivity = now;
if (keyDown) { // just pressed
pressStart = now;
if (beaconOn) stopBeacon();
else setSignal(true); // the LED and buzzer follow your finger
} else { // just released
setSignal(false);
if (ignorePress) { ignorePress = false; return; }
unsigned long unit = unitMs(KEY_WPM);
char symbol = (now - pressStart < DASH_AT_UNITS * unit) ? '.' : '-';
tapped += symbol;
Serial.print(symbol); // show each dot or dash at once
releasedAt = now;
}
}
unsigned long unit = unitMs(KEY_WPM);
if (keyDown && !ignorePress && now - pressStart >= HOLD_FOR_BEACON_MS) startBeacon();
if (!keyDown && tapped.length() > 0 && now - releasedAt >= LETTER_END_UNITS * unit) {
const char* letter = letterFor(tapped.c_str()); // "?" if the dots and dashes mean nothing
Serial.print(" ");
Serial.println(letter);
tappedWord += letter;
tapped = "";
}
if (!keyDown && tappedWord.length() > 0 && now - releasedAt >= WORD_END_UNITS * unit) {
Serial.print("Word: ");
Serial.println(tappedWord);
tappedWord = "";
}
}
// ---------- Deep sleep ----------
void goToSleep() {
Serial.println("Nothing for 3 minutes: sleeping. Press the button to wake me up.");
for (int i = 0; i < 2; i++) { // two blinks = going to sleep
digitalWrite(LED_PIN, HIGH);
delay(150);
digitalWrite(LED_PIN, LOW);
delay(150);
}
// Freeze the buzzer OFF and the LED off during sleep (else the pins could float).
digitalWrite(BUZZER_PIN, !BUZZER_ON);
gpio_hold_en(BUZZER_PIN);
gpio_hold_en(LED_PIN);
gpio_deep_sleep_hold_en();
// Keep the "RTC" part powered so the button's pull-up keeps working (a few microamps).
esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON);
rtc_gpio_init(BUTTON_PIN);
rtc_gpio_set_direction(BUTTON_PIN, RTC_GPIO_MODE_INPUT_ONLY);
rtc_gpio_pullup_en(BUTTON_PIN);
rtc_gpio_pulldown_dis(BUTTON_PIN);
esp_sleep_enable_ext0_wakeup(BUTTON_PIN, LOW); // wake up when the button pulls GPIO27 LOW
Serial.flush();
esp_deep_sleep_start(); // the ESP32 stops here; waking up starts setup() again
}
// ---------- setup(): runs at power-on, reset and every wake-up ----------
void setup() {
setCpuFrequencyMhz(80); // slower = less current. Wi-Fi and Bluetooth stay off.
Serial.begin(115200);
// Unfreeze the outputs, and give the button pin back to normal code.
gpio_hold_dis(BUZZER_PIN);
gpio_hold_dis(LED_PIN);
rtc_gpio_deinit(BUTTON_PIN);
pinMode(BUZZER_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);
setSignal(false);
pinMode(BUTTON_PIN, INPUT_PULLUP); // built-in pull-up: pressed = LOW
if (esp_sleep_get_wakeup_cause() == ESP_SLEEP_WAKEUP_EXT0) waitButtonRelease(); // woken by the button
Serial.println();
Serial.println("Morse spy beacon ready.");
sendAndReport("OK"); // self-test: --- -.- on the LED and buzzer
printHelp();
lastActivity = millis();
}
// ---------- loop(): runs again and again ----------
void loop() {
if (Serial.available()) { // a typed line (the Serial Monitor sends it when you press Enter)
lastActivity = millis();
handleLine(Serial.readStringUntil('\n'));
}
readKey();
if (beaconOn && !keyDown && (long)(millis() - nextBeaconAt) >= 0) {
sendAndReport(beaconMessage.c_str());
nextBeaconAt = millis() + BEACON_PAUSE_MS;
}
if (SLEEP_AFTER_MS > 0 && !beaconOn && !keyDown && millis() - lastActivity >= SLEEP_AFTER_MS) goToSleep();
}
Is the code tested?
The code is compiled automatically every time we change it, so it should build without errors. A real test on real hardware happens when we build this project; until then this sheet stays marked “To test”, and some details (cost, battery life, timing, radio range, light-sensor range) may change. The code assumes the buzzer sounds when its S pin is HIGH. Check this on your own module (step 9) and change the BUZZER_ON constant if it is reversed.
Test checklist
- The board plays OK at power-on
- A typed word is shown in dots and dashes on the monitor and matches the flashes
- Tapping the button makes the LED and buzzer follow your finger, and the right letter appears on the monitor
- A 3 s hold starts the beacon; it repeats every 5 s; one tap stops it
- After a reset, the beacon plays HELLO AGENT again (a typed message is forgotten)
/wpmchanges the speed and/quietsilences the buzzer- After 3 idle minutes the LED blinks twice and the board sleeps; the button wakes it
- On batteries, the pack's red wire is in the
5Vrow and the pack is OFF whenever the USB cable is in
Troubleshooting
Nothing happens when I press EN
I type a message and nothing is sent
/ unless it is a command.The LED works but the buzzer does not (or the other way round)
BUZZER_ON (step 10).My tapped letters come out wrong
The beacon does not start
The board seems dead after a few minutes
SLEEP_AFTER_MS to 0 if you do not want that.The batteries are empty after a night
The radio boards do not hear each other (Go further 1)
GROUP number matches (typing /group 0 on both boards sets them the same). Move them closer. A missing letter just means a lost packet: tap it again.The light receiver misses letters (Go further 2)
Go further 1: Morse by radio between two boards
Two boards, each with the base build, talk to each other by radio. No router, no internet, no password: the boards use a protocol from Espressif called ESP-NOW, which works without an access point. Press the key on one board and the LED and buzzer of the other follow your finger, live.
3 bonus steps · 2 code chunks · Second board needed
Step B1 · Build the second board.
Same base build, same wiring, same holes. Upload the base sketch first to each, to check that each one works alone (steps 8 to 11).
Check: Each board says OK and sends a typed message on its own.
Step B2 · Load the radio sketch on both.
Open “08b-morse-radio” and upload it to both boards, one at a time, with the other unplugged. It is the same sketch on both. Optional: change the
GROUPnumber (0–9) in the code, or type/group 3in the Serial Monitor (until the next reset), so that two pairs in the same room do not hear each other. Both boards of a pair need the same number.Check: Both boards say OK at start-up.
Step B3 · Tap and listen.
Put the boards a few metres apart, both on USB or batteries. Press the button on board A: the LED and buzzer of board B follow your finger. Then type a line in board A's Serial Monitor: board B plays it in Morse and prints it. Swap roles.
Check: Board B copies board A, and the other way round.
Radio delivery is not guaranteed: a packet can get lost, and the sketch does not resend. If a letter is missing, tap it again. Indoors the range is probably tens of metres (typical, to confirm by building). A board listening on batteries uses a lot more current than in the base build (see the table above), so switch it off between games. Same rule as the base: no SOS for fun. This sketch has no beacon mode and no deep sleep: the board listens all the time.
Bonus chunk 1 Sending and receiving by radio
sendPacket()builds a small packet (a tag, the group number and the kind of message: key down, key up or typed text) and broadcasts it to every board in range.onReceive()runs each time a packet arrives: it ignores your own packets and other groups, counts the lost key messages and hands a typed line toloop()to play.startRadio()starts the Wi-Fi radio in station mode (it never joins a network), on channel 1, and registers the broadcast address. What to change:GROUP, or type/group 3, if two pairs share a roomShow the code (55 lines)
// ---------- Radio: send and receive ---------- void sendPacket(uint8_t kind, const char* text) { Packet p; p.tag[0] = 'T'; p.tag[1] = 'M'; p.group = group; p.kind = kind; p.seq = (kind == TEXT) ? 0 : ++mySeq; int len = HEADER_SIZE; if (kind == TEXT) { strncpy(p.text, text, MAX_LINE); p.text[MAX_LINE] = 0; len += strlen(p.text) + 1; // only the letters used, not the whole box } esp_now_send(BROADCAST, (uint8_t*)&p, len); } // Called by the radio each time a message arrives. Keep it short: no delay(), no Morse here. void onReceive(const esp_now_recv_info_t* info, const uint8_t* data, int len) { if (memcmp(info->src_addr, myMac, 6) == 0) return; // our own message: ignore if (len < HEADER_SIZE || len > (int)sizeof(Packet)) return; Packet p; memset(&p, 0, sizeof(p)); memcpy(&p, data, len); if (p.tag[0] != 'T' || p.tag[1] != 'M' || p.group != group) return; // not for us if (p.kind == KEY_DOWN || p.kind == KEY_UP) { if (p.seq == lastSeq) return; // the same message twice if (lastSeq >= 0 && p.seq != (uint8_t)(lastSeq + 1)) lostKeyMessages = lostKeyMessages + 1; lastSeq = p.seq; remoteDown = (p.kind == KEY_DOWN); remoteChangedAt = millis(); } else if (p.kind == TEXT && !textWaiting) { strncpy(incoming, p.text, MAX_LINE); incoming[MAX_LINE] = 0; textWaiting = true; // loop() plays it } } void startRadio() { WiFi.mode(WIFI_STA); // "station" mode, but we never join a Wi-Fi network WiFi.setChannel(RADIO_CHANNEL); while (!WiFi.STA.started()) delay(100); WiFi.macAddress(myMac); if (esp_now_init() != ESP_OK) { Serial.println("ESP-NOW did not start: press EN to restart."); return; } esp_now_register_recv_cb(onReceive); esp_now_peer_info_t peer = {}; // the "every board" address must be added once memcpy(peer.peer_addr, BROADCAST, 6); peer.channel = RADIO_CHANNEL; peer.ifidx = WIFI_IF_STA; peer.encrypt = false; esp_now_add_peer(&peer); }Bonus chunk 2 The key: your button and the other board's
Your button and the other board's button are mixed into one “air” signal. When either is pressed, the LED and buzzer of both boards follow, and both Serial Monitors decode the dots, dashes and letters. If a “released” message is lost, the sound stops by itself after 3 seconds. What to change: nothing
Show the code (40 lines)
// ---------- The key: your button + the other board's button ---------- void updateKey() { unsigned long now = millis(); bool raw = digitalRead(BUTTON_PIN) == LOW; if (raw != lastRaw) { lastRaw = raw; lastChange = now; } if (raw != localDown && now - lastChange >= DEBOUNCE_MS) { localDown = raw; sendPacket(localDown ? KEY_DOWN : KEY_UP, ""); // tell the other board at once } if (remoteDown && now - remoteChangedAt > REMOTE_KEY_TIMEOUT_MS) { remoteDown = false; // the "released" message was lost Serial.println("(radio: a message was lost)"); } bool busy = localDown || remoteDown; // somebody is pressing unsigned long unit = unitMs(KEY_WPM); if (busy != airOn) { airOn = busy; setSignal(airOn); if (airOn) onSince = now; else { char symbol = (now - onSince < DASH_AT_UNITS * unit) ? '.' : '-'; tapped += symbol; Serial.print(symbol); offSince = now; } } if (!airOn && tapped.length() > 0 && now - offSince >= LETTER_END_UNITS * unit) { const char* letter = letterFor(tapped.c_str()); Serial.print(" "); Serial.println(letter); tappedWord += letter; tapped = ""; } if (!airOn && tappedWord.length() > 0 && now - offSince >= WORD_END_UNITS * unit) { Serial.print("Word: "); Serial.println(tappedWord); tappedWord = ""; } }
Make it permanent
On a breadboard, a knock can pull out a wire. Here you solder the same circuit onto a half-size perfboard, plug the ESP32 into sockets (so you can still take it out), put the 4×AA pack underneath, and close it all in a small 3D-printed case. The hole map and the case files are still to come. You need to be ready to solder: it is a good skill and not hard, but the iron is very hot.
Soldering safety
- Lead-free solder with a flux core (0.8 mm is easy to use).
- Iron with a stand and a temperature setting, at 325–375 °C. Turn it down if the solder smokes.
- Ventilation: open a window, or use a small fan with a filter that draws the smoke away from your face.
- Safety glasses: clipped wire ends and solder can fly.
- The iron lives in its stand whenever you are not using it. Never touch the tip or the metal shaft. Work on a heat-proof mat. Unplug the iron when you stop. A burn: cool running water for at least 10 minutes.
- Hold the board with a clamp (“helping hands”), not your fingers.
- Nothing powered while you solder: batteries out of the holder, ESP32 unplugged from its sockets, USB unplugged.
- Wash your hands afterwards, and keep food away from the bench.
- Ask someone who has soldered before to watch your first five joints.
9 steps · +2–3 h · soldering iron · ask for help
Parts for the permanent version
Your base-build parts (ESP32, LED, 220 Ω resistor, buzzer, button, 4×AA holder and cells) move over. You add:
Show the 6 parts
- 1
Breadboard-pattern perfboard, half size×1
Replaces the breadboard
Exact spec: Same rows, 5-hole strips and rails as a breadboard, half size. Exact size to check on the datasheet before you buy; the hole map will match it.
- 2
Female header, 2.54 mm2 strips: 1×40 + 1×20
The ESP32 and the buzzer plug in, and stay removable
Exact spec: Single row, 2.54 mm pitch, long pins. The 1×40 gives the two 19-socket rows for the ESP32, the 1×20 gives the 3-socket row for the buzzer. Cut with a flush cutter; you lose one socket at each cut.
- 3
Screw terminal, 5.0 / 5.08 mm pitch, 2-pole×1
The pack connects without soldering its wires
Exact spec: PCB-mount, wire entry facing out (KF301 / DG301 type).
- 4
Solid hook-up wire, 22 AWG, several colours1 set
Link the holes on the board
Exact spec: Insulated, red, black, orange, green, blue.
- 5
Lead-free solder, flux core1 reel
Joins the parts
Exact spec: 0.8 mm, for example Sn99.3/Cu0.7 or SAC305.
- 6
M3 screwsto confirm with the case files
Close the case and fix the board in it
Exact spec: Counts and heads to confirm once the case is finished.
Tools for the permanent version
Show the 6 tools (1 optional)
Soldering iron with stand and temperature control
Solder the joints
Exact spec: Adjustable, 325–375 °C
Multimeter
Check the joints before power-on (required here)
Exact spec: Continuity beeper, DC volts, diode test
Safety glasses
Protect your eyes from flying clippings
Exact spec: Any clear pair
Helping-hands clamp or board holder
Hold the board while you solder
Exact spec: Any
Flush cutter and wire stripper
Cut the headers and the wires
Exact spec: Any
Small fan with a filter (or an open window)optional
Keep the solder smoke away
Exact spec: Any
The hole map for the half-size perfboard comes with the case files. It will not be a hole-for-hole copy of the 830 breadboard.
Soldering steps
Step P1 · Set up a safe bench. Ask for help
Read the soldering safety list. Window open or fan on, glasses on, iron in its stand on a heat-proof mat, board in the clamp. Ask someone who has soldered before to be there for your first five joints.
Check: Someone experienced is with you, and the iron is hot only when you need it.
Step P2 · Fit the ESP32 and buzzer sockets.
Plug the two 1×19 female headers onto the pins of the ESP32 (this keeps them lined up), place them on the perfboard at the positions on the hole map, turn it over and solder one pin at each end, check it sits flat, then solder the rest. Same for the 3-socket buzzer header. Pull the ESP32 out and put it aside. The hole names come with the hole map.
Check: The sockets stand straight, and each pin is a small shiny cone of solder, not a blob.
Step P3 · Solder the screw terminal, the resistor, the LED and the button.
Terminal for the pack (+ toward the
5Vsocket, − to GND), resistor and LED (long leg toward the resistor), button across the gap. The hole names come with the hole map.Check: The LED's long leg is on the resistor side, and the button sits flat.
Step P4 · Solder the wires.
Insulated 22 AWG wire, flat on the top, soldered from the underside. Same ten wires as the base build: 3V3 and GND rails, buzzer, LED and button. The pack's + goes to the
5Vsocket and never near the 3V3 rail. The wire list with hole names comes with the hole map.Check: All wires are in, and the pack's + wire touches nothing but the
5Vsocket.Step P5 · Look at the underside.
In good light, look for a blob of solder that joins two strips, or a strip and a rail. Remove any blob with the iron (and desoldering braid if you have it).
Check: No bridge between neighbouring joints.
Step P6 · Multimeter checks, pack OFF and ESP32 not plugged in. Ask for help
Continuity (beep) mode. Must NOT beep: + rail to − rail; the
5Vsocket to the + rail; the5Vsocket to the − rail. Must beep: the terminal + to the5Vsocket, the terminal − to GND, the3V3socket to the + rail, theGPIO26socket to the resistor. The button,GPIO27socket to GND, beeps only while pressed.Check: Every “no beep” is silent and every “beep” beeps.
Step P7 · Check the pack, then the key test. Ask for help
Put the cells in the holder, switch ON and read the DC voltage on its wires: +5.6 to +6.5 V (alkaline) or +5.0 to +5.6 V (NiMH). A minus sign means the wires are swapped. Switch OFF and screw the wires into the terminal (red = +). Now the key test, with the ESP32 still unplugged: pack ON, measure the
5Vsocket to GND (you read the pack voltage), then the + rail to GND: it must read 0 V.Check: The + rail reads 0 V. If it shows the pack voltage: STOP. The 5V line touches the 3V3 rail, and it would destroy the ESP32. Switch OFF, find the bridge, fix it.
Step P8 · Plug in the ESP32 and run the tests again.
Pack OFF. Plug the ESP32 into its sockets, USB end first. Switch the pack ON: the red power LED lights and the + rail reads 3.2–3.4 V. Then repeat steps 9 to 14 of the base build on your soldered board.
Check: It behaves exactly like the breadboard version.
Step P9 · Put it in the case.
The case files (a small 3D-printed case for the half-size perfboard) are still to come. The plan: the LED in a 5 mm hole on top (optionally a printed hood so you can aim it), the button reachable on top through a printed plunger, grille holes for the buzzer, the USB port and the pack's switch reachable from outside, a battery door, and a few vent slots. The board draws well under half a watt, so it stays cool, but the vents stay open anyway.
Check: The button, the LED, the USB port and the pack's switch are all reachable, and the vent slots are open.
3D files
Files to come: small case for the half-size perfboard, button plunger, optional LED hood, battery door.
Go further 2: read Morse with a light sensor
A second board looks at the first board's LED with a light sensor and decodes the flashes into letters. Same trick as a signal lamp between two ships, with an ESP32 as the sailor.
4 bonus steps · 2 code chunks · Second board + LDR · Level 2
Wire list
| # | Colour | From | To |
|---|---|---|---|
| R1 | red | LDR leg 1 | 3V3 rail |
| R2 | blue | LDR leg 2 and 10 kΩ resistor leg 1 (same row) | GPIO34 (j15) |
| R3 | black | 10 kΩ resistor leg 2 | GND rail |
The brighter the light on the LDR, the higher the voltage on GPIO34, never above 3.3 V, so it is safe. Slide the opaque tube over the LDR and point it at the sender's LED, 5–30 cm away. Use it in a dim room.
Step L1 · Build the receiver board.
Base build plus wires R1 to R3. Keep the buzzer, the LED and the button: the receiver also mirrors what it sees.
Check: The LDR is wired as in the table, and nothing else touches
GPIO34.Step L2 · Load the light-receiver sketch.
Upload “08c-morse-light” to the receiver board. The sender keeps the base sketch.
Check: At start-up the monitor says the receiver is calibrating.
Step L3 · Calibrate.
Switch the receiver on with the sender's LED off. For 2 seconds it learns how dark your room is. Then make the sender flash (tap its button, or type E in its Serial Monitor): the first bright reading sets the cut-off between dark and light. Point the tube at the LED. If you move the boards or the room light changes, type
/calor press the receiver's button to calibrate again.Check: The monitor shows the dark and bright levels, then “Ready: listening for Morse light.”
Step L4 · Send and read.
On the sender, type a message at its default speed, 10 WPM: that is the speed the receiver expects (
RX_WPM). It reads senders from 7 to 12 WPM, but the LDR lags above 10, so stay at 10 WPM or less. To read a slower sender, give the receiver the same speed with/wpm(5 to 10). The receiver prints the letters and mirrors them on its own LED and buzzer.Check: The letters on the receiver match the message.
An LDR reacts slowly (tens of milliseconds, typical), so keep the sender at 10 WPM or less. Direct sunlight or a flickering lamp can fool it: use a dim room and a short tube. No laser here: the LED is the light of this mission.
Bonus chunk 1 Learning dark and bright
calibrate()averages the light sensor for 2 seconds with the sender's LED off (the dark level), waits for the first clearly brighter reading (at leastMIN_JUMPhigher), keeps the brightest value for 50 ms as the bright level and sets the cut-off halfway between the two. It then waits for that flash to end so it is not decoded. What to change:MIN_JUMP, if your room is very brightShow the code (44 lines)
// ---------- Calibration: learn "dark" and "bright" ---------- void calibrate() { setSignal(false); Serial.println("Calibration: keep board A's LED OFF for 2 seconds..."); delay(500); long sum = 0; int count = 0; unsigned long start = millis(); while (millis() - start < 2000) { // average of many readings = the dark level sum += analogRead(LIGHT_PIN); count++; delay(SAMPLE_MS); } darkLevel = sum / count; Serial.print("Dark level: "); Serial.println(darkLevel); Serial.println("Now make board A flash (tap its button, or type E in its Serial Monitor)..."); unsigned long lastHint = millis(); int v = analogRead(LIGHT_PIN); while (v < darkLevel + MIN_JUMP) { // wait for a clearly brighter reading if (millis() - lastHint > 5000) { Serial.println("...still waiting for a flash (aim the tube at the LED, dim the room)"); lastHint = millis(); } delay(SAMPLE_MS); v = analogRead(LIGHT_PIN); } // The LDR needs a few ms to reach full brightness: keep the highest reading for 50 ms. brightLevel = v; for (int i = 0; i < 25; i++) { int r = analogRead(LIGHT_PIN); if (r > brightLevel) brightLevel = r; delay(SAMPLE_MS); } printLevels(); // Wait for the end of that flash, so it is not decoded. while (analogRead(LIGHT_PIN) > (darkLevel + brightLevel) / 2) delay(SAMPLE_MS); lightOn = false; offSince = millis(); tapped = ""; tappedWord = ""; Serial.println("Ready: listening for Morse light."); }Bonus chunk 2 From light to letters
readLight()reads the sensor every 2 ms and decides on or off with the cut-off plus a 10 % band against flicker. Light on is like a pressed key: it times each flash and gap like the button decoder of the base sketch, but cuts at the midpoints (2, 2 and 5 units), because the slow LDR stretches flashes and shrinks gaps. The dark and bright levels follow slowly, and it calibrates again if they get too close. AtRX_WPM= 10 it reads senders from 7 to 12 WPM. What to change:RX_WPM(or/wpmon the receiver, 5 to 10)Show the code (49 lines)
// ---------- Reading the light: on or off? ---------- void readLight() { int v = analogRead(LIGHT_PIN); int span = brightLevel - darkLevel; int threshold = darkLevel + span / 2; // halfway between dark and bright int margin = span / 20; // +/- 5 % = 10 % "hysteresis" band against flicker unsigned long now = millis(); unsigned long unit = unitMs(rxWpm); if (!lightOn && v > threshold + margin) { // the light just came on lightOn = true; onSince = now; peak = v; setSignal(true); } else if (lightOn && v < threshold - margin) { // the light just went off lightOn = false; setSignal(false); char symbol = (now - onSince < DASH_AT_UNITS * unit) ? '.' : '-'; tapped += symbol; Serial.print(symbol); offSince = now; // Adaptive threshold: move the bright level a quarter of the way toward this flash. brightLevel = brightLevel + (peak - brightLevel) / 4; } else if (lightOn) { if (v > peak) peak = v; // remember the brightest reading of this flash } else { // Light off: follow the room light slowly (1/64 of the difference each reading). darkLevel = darkLevel + (v - darkLevel) / 64; } if (brightLevel - darkLevel < MIN_JUMP / 2) { // the two levels got too close Serial.println(); Serial.println("Signal too weak: measuring again."); calibrate(); return; } if (!lightOn && tapped.length() > 0 && now - offSince >= LETTER_END_UNITS * unit) { const char* letter = letterFor(tapped.c_str()); Serial.print(" "); Serial.println(letter); tappedWord += letter; tapped = ""; } if (!lightOn && tappedWord.length() > 0 && now - offSince >= WORD_END_UNITS * unit) { Serial.print("Word: "); Serial.println(tappedWord); tappedWord = ""; } }
Go further
Later idea (not built yet): the same beacon on a tiny ESP32-C3 SuperMini board, pocket-sized and running for months on cells. It is a Level 2 build, like the pocket version of mission 01.
You can reuse your LED, buzzer and button.
Shopping list
Made from the parts and tools lists above, with quantities. Each line opens an Amazon.ca search; Amazon has no multi-item cart link without exact product codes, so you add items one by one. Copy the list to keep it.
Each link opens a plain Amazon.ca search built from the keywords (not an affiliate link). Pick a listing that matches the exact spec in the parts list.
Show the 29 items
- ×1ESP32 boardAmazon.ca
- ×1BreadboardAmazon.ca
- ×1Yellow LED, 5 mmAmazon.ca
- ×1220 Ω resistorAmazon.ca
- ×1Active buzzer moduleAmazon.ca
- ×1Push buttonAmazon.ca
- about 10Jumper wiresAmazon.ca
- ×1USB data cableAmazon.ca
- ×14×AA battery holder with ON/OFF switch, cover and header-pin ends (optional)Amazon.ca
- ×4AA batteries (optional)Amazon.ca
- 1 setSecond complete base kit (board, breadboard, LED, 220 Ω, buzzer, button, wires, USB cable) (optional)Amazon.ca
- ×1Light-dependent resistor (LDR), GL5528 type (optional)Amazon.ca
- ×110 kΩ resistor (optional)Amazon.ca
- ×1Short opaque tube, 3–5 cm (optional)Amazon.ca
- ×1Computer with Arduino IDE—
- ×1Sticky label and a pen (optional)Amazon.ca
- ×1Multimeter (optional)Amazon.ca
- ×1Breadboard-pattern perfboard, half size (Make it permanent)Amazon.ca
- 2 strips: 1×40 + 1×20Female header, 2.54 mm (Make it permanent)Amazon.ca
- ×1Screw terminal, 5.0 / 5.08 mm pitch, 2-pole (Make it permanent)Amazon.ca
- 1 setSolid hook-up wire, 22 AWG, several colours (Make it permanent)Amazon.ca
- 1 reelLead-free solder, flux core (Make it permanent)Amazon.ca
- to confirm with the case filesM3 screws (Make it permanent)Amazon.ca
- ×1Soldering iron with stand and temperature control (Make it permanent)Amazon.ca
- ×1Multimeter (Make it permanent)Amazon.ca
- ×1Safety glasses (Make it permanent)Amazon.ca
- ×1Helping-hands clamp or board holder (Make it permanent)Amazon.ca
- ×1Flush cutter and wire stripper (Make it permanent)Amazon.ca
- ×1Small fan with a filter (or an open window) (Make it permanent) (optional)Amazon.ca
Morse spy beacon 1 × ESP32 board — ESP32-DevKitC V4 or a clone: ESP32-WROOM-32, 38 pins, 3.3 V logic. Check the regulator before you run it on 4 alkaline cells (step 2): the 3-legged chip with a big tab near the 5V pin should say AMS1117. https://www.amazon.ca/s?k=ESP32+DevKitC+38+pin+WROOM-32+AMS1117 1 × Breadboard — Full-size 830 points. A 38-pin board plus its parts will not fit on a 400-point board. https://www.amazon.ca/s?k=830+point+breadboard 1 × Yellow LED, 5 mm — 5 mm, any “bright” yellow. Forward voltage about 2.0–2.2 V (typical, check on your LED's datasheet). Yellow is easy to see and different from mission 01's red, but any colour works with the same resistor. https://www.amazon.ca/s?k=5mm+LED+yellow+high+brightness 1 × 220 Ω resistor — 220 Ω, 1/4 W, through-hole. About (3.3 − 2.1) / 220 ≈ 5.5 mA: bright enough indoors and far below the usual 20 mA LED rating. https://www.amazon.ca/s?k=220+ohm+resistor+1%2F4W 1 × Active buzzer module — Active (built-in tone) module, 3 pins S / + / −, 3.3–5 V, sounds when S is HIGH. Some modules are the other way round: you test it in step 9 and can fix it in step 10. Takes roughly 20–30 mA (typical, to confirm on your module). https://www.amazon.ca/s?k=active+buzzer+module+3+pin+5V 1 × Push button — 6 mm tactile switch, 4 legs. No resistor needed: the code turns on the board's internal pull-up. https://www.amazon.ca/s?k=6mm+tactile+push+button about 10 × Jumper wires — Male-to-male, about 10–20 cm. https://www.amazon.ca/s?k=male+to+male+jumper+wires 1 × USB data cable — Data cable (not charge-only) matching the board's port. https://www.amazon.ca/s?k=USB+data+cable+micro+USB 1 × 4×AA battery holder with ON/OFF switch, cover and header-pin ends (optional) — Same holder as mission 01 (Adafruit 830 type). Fresh alkaline cells give about 6.4 V, flat ones about 4 V. The board needs about 4.4–6.5 V, so change the cells before they get that low. A 3×AA holder is not enough: it starts at 4.5 V and drops below the limit almost at once. https://www.amazon.ca/s?k=4+AA+battery+holder+switch+cover+header+pins+breadboard 4 × AA batteries (optional) — Alkaline AA (LR6), or low-self-discharge NiMH AA. Same type and brand, never mixed. 4×NiMH only if your regulator is not an AMS1117 (step 2). https://www.amazon.ca/s?k=AA+alkaline+batteries+8+pack 1 set × Second complete base kit (board, breadboard, LED, 220 Ω, buzzer, button, wires, USB cable) (optional) — Identical to the base build. A friend's board works, as long as it is a 38-pin ESP32 with the same wiring. https://www.amazon.ca/s?k=ESP32+DevKitC+38+pin+WROOM-32 1 × Light-dependent resistor (LDR), GL5528 type (optional) — GL5528 or similar. A little slow (tens of milliseconds, typical, check the datasheet), which is why this option stays at 10 WPM or less. Contains cadmium sulfide (see Safety). https://www.amazon.ca/s?k=GL5528+LDR+photoresistor 1 × 10 kΩ resistor (optional) — 10 kΩ, 1/4 W, through-hole https://www.amazon.ca/s?k=10k+ohm+resistor+1%2F4W 1 × Short opaque tube, 3–5 cm (optional) — A drinking straw wrapped in black tape, a roll of black paper, or a printed tube. https://www.amazon.ca/s?k=black+heat+shrink+tube+6mm 1 × Computer with Arduino IDE — Arduino IDE 2.x + “esp32 by Espressif” 3.3.x (free download from arduino.cc) 1 × Sticky label and a pen (optional) — Any https://www.amazon.ca/s?k=sticky+labels 1 × Multimeter (optional) — Any basic digital multimeter https://www.amazon.ca/s?k=digital+multimeter+basic 1 × Breadboard-pattern perfboard, half size (Make it permanent) — Same rows, 5-hole strips and rails as a breadboard, half size. Exact size to check on the datasheet before you buy; the hole map will match it. https://www.amazon.ca/s?k=half+size+perma-proto+breadboard+PCB 2 strips: 1×40 + 1×20 × Female header, 2.54 mm (Make it permanent) — Single row, 2.54 mm pitch, long pins. The 1×40 gives the two 19-socket rows for the ESP32, the 1×20 gives the 3-socket row for the buzzer. Cut with a flush cutter; you lose one socket at each cut. https://www.amazon.ca/s?k=female+header+1x40+2.54mm 1 × Screw terminal, 5.0 / 5.08 mm pitch, 2-pole (Make it permanent) — PCB-mount, wire entry facing out (KF301 / DG301 type). https://www.amazon.ca/s?k=screw+terminal+block+5.08mm+2+pin 1 set × Solid hook-up wire, 22 AWG, several colours (Make it permanent) — Insulated, red, black, orange, green, blue. https://www.amazon.ca/s?k=22+AWG+solid+core+hook+up+wire+kit 1 reel × Lead-free solder, flux core (Make it permanent) — 0.8 mm, for example Sn99.3/Cu0.7 or SAC305. https://www.amazon.ca/s?k=lead+free+solder+flux+core+0.8mm to confirm with the case files × M3 screws (Make it permanent) — Counts and heads to confirm once the case is finished. https://www.amazon.ca/s?k=M3+screws+standoffs+assortment 1 × Soldering iron with stand and temperature control (Make it permanent) — Adjustable, 325–375 °C https://www.amazon.ca/s?k=soldering+iron+adjustable+temperature+stand 1 × Multimeter (Make it permanent) — Continuity beeper, DC volts, diode test https://www.amazon.ca/s?k=digital+multimeter+continuity+beep 1 × Safety glasses (Make it permanent) — Any clear pair https://www.amazon.ca/s?k=safety+glasses+clear 1 × Helping-hands clamp or board holder (Make it permanent) — Any https://www.amazon.ca/s?k=helping+hands+PCB+holder 1 × Flush cutter and wire stripper (Make it permanent) — Any https://www.amazon.ca/s?k=flush+cutter+wire+stripper 1 × Small fan with a filter (or an open window) (Make it permanent) (optional) — Any https://www.amazon.ca/s?k=solder+fume+extractor+fan
Sources
Show the 11 sources
- ITU-R M.1677-1 (10/2009), International Morse code: signal lengths and spacing (dash = 3 dots, gaps of 1, 3 and 7 units).
- sigrok libsigrokdecode, Morse decoder (quotes ITU-R M.1677-1 section 2 on spacing and the character table)
- Espressif, ESP32 datasheet (3.6 V maximum, pin currents, pull-up, power modes, Wi-Fi receive current, GPIO34 = ADC1 input-only)
- ESP-IDF, ESP-NOW (connectionless, up to 250 bytes per message (ESP-NOW v1.0), delivery not guaranteed)
- Arduino-ESP32, ESP-NOW API and broadcast examples (works without an access point)
- SparkFun, Light-Emitting Diodes (20 mA typical continuous rating, forward voltage)
- ESP-IDF, Sleep modes (wake-up from deep sleep on a button, ext0)
- Arduino-ESP32, ADC API (11 dB range, about 150–3100 mV)
- Adafruit product 830, 4×AA holder with on/off switch (voltages, pin ends)
- Espressif, ESP32-DevKitC V4 user guide (power options: only one at a time)
- SparkFun, How to Solder: Through-Hole Soldering (temperature, glasses, helping hands)
Not sourced yet: Estimates, not sourced: battery life and AA capacities, the 4.4 V lower limit, yellow LED forward voltage, buzzer current, LDR response time and cadmium note, regulator quiet current, the range of ESP-NOW indoors, the PARIS convention. Measure on your build.
Print the sheet Print the project recap sheet
A print-ready version: parts checklist, wiring table and diagram, every step with its picture.
Built it?
I built this
Coming soon: a simple, anonymous count of builds. Nothing is collected for now.