// Tinker Mission — Mission 08, go further 1: Morse by radio between two ESP32s (ESP-NOW) // Board: ESP32 Dev Module ("esp32 by Espressif" 3.3.x). No extra library needed. // // You need TWO base builds (same wiring as mission 08) and this same sketch on both boards. // ESP-NOW lets ESP32 boards send short messages to each other by radio, directly: no router, // no internet, no password. Each board shouts ("broadcasts") to every board around. // // How it works: // - Press your button: the LED and buzzer of BOTH boards follow your finger, and both Serial // Monitors show the dots, dashes and letters that went "on the air". // - Type a line in the Serial Monitor (115200 baud, "Newline"): it is sent by radio, and both // boards play it in Morse. // Radio messages can get lost (nobody checks they arrived). If a letter is missing, tap it again. // // Commands: /wpm 15 (speed 5-20) /quiet /loud /group 3 (0-9) /help // Two pairs of boards in the same room? Give each pair its own group number, so they do not mix. // // Wiring (each board, ESP32 DevKitC, 38 pins), the same as mission 08: // 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) // No deep sleep here: the radio must listen all the time, so batteries last about a day. #include // starts the radio part of the ESP32 #include // ESP-NOW: short radio messages between ESP32 boards // ---------- Pins ---------- const int BUTTON_PIN = 27; // pressed = LOW (wired to GND) const int LED_PIN = 26; const int BUZZER_PIN = 25; // ---------- Settings you may change ---------- const int BUZZER_ON = HIGH; // change to LOW if your buzzer beeps all the time const int SEND_WPM = 10; // speed for typed messages, in words per minute const int KEY_WPM = 8; // how fast we expect people to tap the button const int GROUP = 0; // 0 to 9: boards only listen to boards of the same group const int RADIO_CHANNEL = 1; // Wi-Fi channel 1 to 13: the same on both boards const int MAX_LINE = 100; // longest typed message (ESP-NOW allows up to 250 bytes) const unsigned long REMOTE_KEY_TIMEOUT_MS = 3000; // "released" message lost? stop beeping after 3 s // How the 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; // ---------- 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; } // ---------- What travels by radio ---------- // Every radio message starts with "TM" (Tinker Mission), the group number and its kind. const uint8_t KEY_DOWN = 'D', KEY_UP = 'U', TEXT = 'T'; struct Packet { char tag[2]; // always 'T', 'M': ignore radio messages from other gadgets uint8_t group; // 0 to 9 uint8_t kind; // KEY_DOWN, KEY_UP or TEXT uint8_t seq; // counts the key messages, to notice the lost ones char text[MAX_LINE + 1]; // the typed message (TEXT only) }; const int HEADER_SIZE = 5; // tag + group + kind + seq uint8_t BROADCAST[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; // "to every board" // ---------- Variables ---------- int sendWpm = SEND_WPM; bool quiet = false; int group = GROUP; uint8_t myMac[6]; // this board's radio address uint8_t mySeq = 0; // Written by onReceive() (it runs in the radio's own task), read by loop(): "volatile". volatile bool remoteDown = false; // the other board's button is pressed volatile unsigned long remoteChangedAt = 0; volatile int lostKeyMessages = 0; volatile bool textWaiting = false; char incoming[MAX_LINE + 1]; int lastSeq = -1; // last key message number received (-1 = none yet) // Local button and "the air" (on when anyone presses) bool localDown = false, lastRaw = false, airOn = false; unsigned long lastChange = 0, onSince = 0, offSince = 0; String tapped = ""; // dots and dashes of the letter on the air String tappedWord = ""; // letters of the word on the air // ---------- Small helpers ---------- void setSignal(bool on) { digitalWrite(LED_PIN, on ? HIGH : LOW); digitalWrite(BUZZER_PIN, (on && !quiet) ? BUZZER_ON : !BUZZER_ON); } bool waitOrPress(unsigned long ms) { // waits, but returns true at once if the button is pressed unsigned long start = millis(); while (millis() - start < ms) { if (digitalRead(BUTTON_PIN) == LOW) return true; delay(1); } return false; } void printHelp() { Serial.println("Type a message and press Enter: it goes by radio and both boards play it."); Serial.println("Press the button: both boards beep with your finger."); Serial.println("Commands: /wpm 15 /quiet /loud /group 3 /help"); } // Plays a text in Morse (same rules as mission 08). Returns true if the button stopped it. bool sendMorse(const char* text) { unsigned long unit = unitMs(sendWpm); int gapBefore = 0; 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; 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); } void printMorse(const char* text) { // "SOS -> ... --- ..." 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) { Serial.print(" "); Serial.print(code); } } Serial.println(); } void play(const char* text) { if (sendMorse(text)) { Serial.println("Stopped by the button."); while (digitalRead(BUTTON_PIN) == LOW) delay(10); delay(50); } } // ---------- 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); } // ---------- Typed lines and commands ---------- void handleLine(String line) { line.trim(); if (line.length() == 0) return; if (line.startsWith("/wpm")) { sendWpm = constrain(line.substring(4).toInt(), 5, 20); Serial.print("Speed: "); Serial.println(sendWpm); } else if (line.startsWith("/group")) { group = constrain(line.substring(6).toInt(), 0, 9); Serial.print("Group: "); Serial.println(group); } else if (line == "/quiet") { quiet = true; Serial.println("Buzzer off"); } 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."); } sendPacket(TEXT, line.c_str()); Serial.print("Sent by radio: "); printMorse(line.c_str()); play(line.c_str()); } } // ---------- 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 = ""; } } // ---------- setup() and loop() ---------- void setup() { Serial.begin(115200); pinMode(LED_PIN, OUTPUT); pinMode(BUZZER_PIN, OUTPUT); setSignal(false); pinMode(BUTTON_PIN, INPUT_PULLUP); startRadio(); Serial.println(); Serial.print("Morse radio ready, group "); Serial.println(group); play("OK"); printHelp(); } void loop() { if (Serial.available()) handleLine(Serial.readStringUntil('\n')); if (textWaiting) { Serial.print("Received: "); printMorse(incoming); play(incoming); textWaiting = false; } if (lostKeyMessages > 0) { Serial.println("(radio: a message was lost - if a letter is missing, tap it again)"); lostKeyMessages = 0; } updateKey(); }