typestar

morse_beacon.ino in Arduino

Blink a message in Morse from an A-Z lookup table.

// Blink a message in Morse from a lookup table, letter by letter.

const int BEACON_PIN = LED_BUILTIN;
const int UNIT_MS = 120;
const char MESSAGE[] = "SOS HELP";

// A-Z as dot-dash strings; index by letter minus 'A'.
const char* CODE[26] = {
  ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....",
  "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.",
  "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-",
  "-.--", "--..",
};

void flash(unsigned long onMs) {
  digitalWrite(BEACON_PIN, HIGH);
  delay(onMs);
  digitalWrite(BEACON_PIN, LOW);
  delay(UNIT_MS);  // gap between symbols
}

void sendLetter(char letter) {
  if (letter == ' ') {
    delay(UNIT_MS * 7);  // word gap
    return;
  }
  const char* symbols = CODE[letter - 'A'];
  for (int i = 0; symbols[i] != '\0'; i++) {
    flash(symbols[i] == '.' ? UNIT_MS : UNIT_MS * 3);
  }
  delay(UNIT_MS * 3);  // letter gap
}

void setup() {
  pinMode(BEACON_PIN, OUTPUT);
}

void loop() {
  for (int i = 0; MESSAGE[i] != '\0'; i++) {
    sendLetter(MESSAGE[i]);
  }
  delay(UNIT_MS * 14);
}

How it works

  1. CODE[26] maps letters to dot-dash strings, indexed by - 'A'.
  2. flash times a symbol; gaps follow the 1-3-7 unit rule.
  3. sendLetter walks the symbol string char by char.

Keywords and builtins used here

The run, in numbers

Lines
43
Characters to type
1009
Tokens
322
Three-star pace
60 tpm

At the three-star pace of 60 tokens a minute, this run takes about 322 seconds.

Type this snippet

Step 3 of 3 in Encore, step 27 of 27 in Language basics.

← Previous