TinkerBlock UNO kit/Sound/13. Lab: a Morse code key
Sound · 13 of 21

Lab: a Morse code key

The push button becomes a Morse key. The XL LED and the active buzzer follow it, and the sketch times every press and every silence in dots, the unit the ITU defines Morse by, to turn them into letters on the Serial Monitor.

The button is the key, the lamp and the buzzer are the signal, and the sketch is the listener. The three modules have their own books, the TK04, the TK01 and the TK36; the timing leans on millis() and debouncing.

Where they plug in

ModuleSocketPin
TK04 push buttonD6/D7D7
TK01 XL LEDD2/D3D3
TK36 active buzzerD10/D11D11

The active buzzer makes its own tone, about 2.4 kHz, whenever its pin is HIGH, so the sketch drives it with digitalWrite like the lamp. It needs no timer, which leaves Timer2 free for the next lab's tone().

Morse is measured in dots

Morse has one unit, the length of a dot, and every other length is a whole number of them. The ITU's recommendation, M.1677-1, sets the ratios:

Dots
Dot1
Dash3
Gap between signs of one letter1
Gap between letters3
Gap between words7

A key only ever says two things, down or up, so the sketch reads a message entirely from how long each lasted. It decides at the midpoints. A press shorter than 2 dots is a dot, anything longer a dash. A silence that reaches 2 dots is longer than any gap inside a letter, so the letter is over and the sketch looks it up. One that reaches 5 dots is longer than any gap between letters, so a word is over.

A key, timed in dots
Key
Key
up
Serial Monitor
nothing yet
Dot
120 ms
Speed
10 words a minute
Each press becomes a dot or a dash by its length alone: under 2 dots is a dot. A silence of 2 dots ends the letter, which is when the sketch looks it up and prints it.

Key SOS and the letters appear two dots into each silence, not three: the sketch does not wait for the full gap, only for the moment it can no longer be anything else. SOS, dashes too short holds each dash for 1.8 dots. Every one falls under the line, the O comes out as a fourth S, and nothing in the sketch has failed: it heard exactly what was keyed.

The sketch's dot is 120 ms. Speeds are counted in the word PARIS, which is 50 dots long with its word gap, so 120 ms a dot is 6 s a word: ten words a minute.

The sketch

The ATmega328P book debounces with a 50 ms lockout after each edge. A key wants something different, because the length of every press is the message: here a new level counts once it has lasted 20 ms, and the sketch keeps the date of the edge. It takes the time the level began to change, rawAt, not the time it was accepted, so the 20 ms delay falls on both ends of a press and cancels out of its length:

unsigned long lasted = rawAt - edgeAt;   // how long the last state held
edgeAt = rawAt;
...
if (!down && count < sizeof(signs) - 1) {
  signs[count++] = lasted < DASH_FROM ? '.' : '-';
}

On release the press becomes a . or a - in signs. While the key is up, the length of the silence decides: past LETTER_FROM the signs are compared with the 36 codes, letters A to Z and figures 0 to 9, and the match is printed; past WORD_FROM a space follows. Nothing in loop() waits, so the lamp answers the key within the 20 ms of the debounce however long a silence has been.

Make it yours

  • Print the signs as they are keyed, Serial.print(signs[count - 1]), to see the dots and dashes before the letter is decided.
  • Turn it round: a string in the sketch, played out on the lamp and buzzer with the same table and the same ratios, is a beacon.
  • Add punctuation: M.1677-1 also lists the full stop (.-.-.-) and the question mark (..--..); add both strings to the two tables.

The code

Morse_Key.ino

Key with the button. The lamp and the buzzer follow it; the Serial Monitor at 115200 baud prints each letter once the silence after it is two dots long, and a space once it is five.

// Morse_Key.ino: the push button is a Morse key. The XL LED and
// the active buzzer follow it, and the sketch times every press
// and every silence and prints the letters to the Serial Monitor.
//
// Wiring, on the TinkerBlock UNO shield:
//   TK04 push button in the D6/D7 socket, so it is on D7
//   TK01 XL LED in the D2/D3 socket, so it is on D3
//   TK36 active buzzer in the D10/D11 socket, so it is on D11
// Tools > Board: Arduino Uno
// Tools > Port: the CH340 port
// Serial Monitor: 115200 baud
// No library.
//
// Timing in dots, ITU-R M.1677-1: a dash is 3 dots; the gap
// inside a letter 1, between letters 3, between words 7. The
// sketch decides at the midpoints: under 2 dots is a dot, a
// silence of 2 dots ends the letter, of 5 dots the word.

const byte KEY = 7;
const byte LED = 3;
const byte BUZZER = 11;

const unsigned long DOT_MS = 120;            // 10 words a minute
const unsigned long DASH_FROM = 2 * DOT_MS;
const unsigned long LETTER_FROM = 2 * DOT_MS;
const unsigned long WORD_FROM = 5 * DOT_MS;
const unsigned long DEBOUNCE_MS = 20;

const char LETTERS[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
const char *const CODES[] = {
  ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..",
  ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.",
  "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..",
  ".----", "..---", "...--", "....-", ".....",
  "-....", "--...", "---..", "----.", "-----"
};
const byte CODE_COUNT = sizeof(CODES) / sizeof(CODES[0]);

char signs[8];               // the dots and dashes of this letter
byte count = 0;
bool wordOpen = false;       // a letter was sent since the last space

bool raw = LOW;              // what the pin read last
unsigned long rawAt = 0;     // when that reading began
bool down = false;           // the key, debounced
unsigned long edgeAt = 0;    // when the key last went down or up

char decode() {
  signs[count] = '\0';
  for (byte i = 0; i < CODE_COUNT; i++) {
    if (strcmp(signs, CODES[i]) == 0) return LETTERS[i];
  }
  return '?';
}

void setup() {
  pinMode(LED, OUTPUT);
  pinMode(BUZZER, OUTPUT);
  digitalWrite(BUZZER, LOW);   // the TK36 has no pull-down
  pinMode(KEY, INPUT);         // the TK04 has its own pull-down
  Serial.begin(115200);
  Serial.println("Key away. Dot 120 ms, dash 360 ms.");
}

void loop() {
  unsigned long now = millis();

  // Debounce: accept a new level once it has lasted 20 ms, and
  // date the edge from when it began.
  bool reading = digitalRead(KEY);
  if (reading != raw) {
    raw = reading;
    rawAt = now;
  }
  if (raw != down && now - rawAt >= DEBOUNCE_MS) {
    unsigned long lasted = rawAt - edgeAt;
    edgeAt = rawAt;
    down = raw;
    digitalWrite(LED, down);
    digitalWrite(BUZZER, down);

    if (!down && count < sizeof(signs) - 1) {
      signs[count++] = lasted < DASH_FROM ? '.' : '-';
    }
  }

  // While the key is up, the silence decides.
  if (!down) {
    unsigned long quiet = now - edgeAt;
    if (count > 0 && quiet >= LETTER_FROM) {
      Serial.print(decode());
      count = 0;
      wordOpen = true;
    }
    if (wordOpen && quiet >= WORD_FROM) {
      Serial.print(' ');
      wordOpen = false;
    }
  }
}

DOT_MS sets the speed: 120 ms is ten words a minute. If your dashes keep coming out as dots, raise it to 150 or 200 and the sketch waits for longer presses. Every other number is a multiple of it.

View on GitHub · kits/tkbu/morse-code/Morse_Key/Morse_Key.ino @ v1.14

When it does not work

Every press comes out as a dot.

A dash has to be held for at least two dots, 240 ms at the sketch's speed. A quick hand holds it for less. Hold dashes longer, or raise DOT_MS so the line between dot and dash moves out to where your hand puts it.

Letters come out split in two, an A as E T.

The gap between the dot and the dash lasted two dots or more, so the sketch ended the letter in the middle. Inside a letter the gap is one dot; key the signs of one letter closer together, or raise DOT_MS.

The buzzer sounds but the lamp stays dark, or the other way round.

Check the sockets: the XL LED in D2/D3, on D3; the active buzzer in D10/D11, on D11. Both modules have their signal on their fourth pin, so a module in the wrong socket is on a pin the sketch never drives.

Nothing happens when I press the button.

The button must be in the D6/D7 socket, so it is on D7. The TK04 reads HIGH when pressed and has its own pull-down, so the sketch uses plain INPUT. Watch the button's own lamp: if it lights on a press, the module works and the socket or cable is the suspect.

The Serial Monitor shows question marks.

The signs of that letter are not in the table: four dots and a dash, say. The sketch prints ? rather than guessing. The figure's third case shows how one short dash turns a known letter into another.

Where this goes next

The passive buzzer plays three tunes, every note worked out from one formula.

Lab: a melody player →

Edit this page — content/books/tkbu/morse-code.mdx

Community

Questions about this product

See what other owners have asked, and read their solutions.

Ask a question ↗

TinkerBlock UNO R3 Starter Kit, 12 Modules

Loading discussions…

Discuss this article

Ask about this page. The answer stays here, on the page it belongs to, for whoever hits the same wall next.

Browse Modules and blocks on the forum →