Skip to content

Instantly share code, notes, and snippets.

@MarioLiebisch
Created March 24, 2020 13:52
Show Gist options
  • Save MarioLiebisch/43d67ddc9271493e33e2592e19675522 to your computer and use it in GitHub Desktop.
Save MarioLiebisch/43d67ddc9271493e33e2592e19675522 to your computer and use it in GitHub Desktop.
Simplified Morse Code Generator for Arduino
// Pins used for this
#define LED_PIN 13
#define BUZZER_PIN 11
// The time in milliseconds for short signals
#define TIME_UNIT 100
// Frequency used
// For classic codes both should match
#define FREQUENCY_LONG 220
#define FREQUENCY_SHORT 440
const char *code[256] = {0};
// Signal a short code and wait
void signalShort() {
digitalWrite(LED_PIN, HIGH);
tone(BUZZER_PIN, FREQUENCY_SHORT);
delay(1 * TIME_UNIT);
digitalWrite(LED_PIN, LOW);
noTone(BUZZER_PIN);
delay(1 * TIME_UNIT);
}
// Signal a long code and wait
void signalLong() {
digitalWrite(LED_PIN, HIGH);
tone(BUZZER_PIN, FREQUENCY_LONG);
delay(3 * TIME_UNIT);
digitalWrite(LED_PIN, LOW);
noTone(BUZZER_PIN);
delay(1 * TIME_UNIT);
}
// "Signal" the delay between characters
// (3 units long, but 1 unit is paused after last character)
void signalNext() {
delay(2 * TIME_UNIT);
}
// Signal a space between words
// (7 units long, but 1 unit is paused after last character)
void signalSpace() {
delay(6 * TIME_UNIT);
}
void morse(const char c) {
// Handle space
if (c == ' ') {
signalSpace();
return;
}
// Get a code for other characters
const char *signals = code[tolower(c)];
// Test if signal is defined
if (signals && *signals) {
// Go through all components
while (*signals) {
// Determine what to do
switch (*signals++) {
case '.':
case 's':
case 'k':
signalShort();
break;
case '-':
case 'l':
signalLong();
break;
}
}
}
}
void morse(const char *text) {
// Iterate over all characters and morse them
while (*text) {
morse(*text++);
// Wait for next character (if any)
if (*text) {
signalNext();
}
}
}
void setup() {
// Set output pins
pinMode(LED_PIN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
// Define morse code table
code['a'] = ".-";
code['b'] = "-...";
code['c'] = "-.-.";
code['d'] = "-..";
code['e'] = ".";
code['f'] = "..-.";
code['g'] = "--.";
code['h'] = "....";
code['i'] = "..";
code['j'] = ".---";
code['k'] = "-.-";
code['l'] = ".-..";
code['m'] = "--";
code['n'] = "-.";
code['o'] = "---";
code['p'] = ".--.";
code['q'] = "--.-";
code['r'] = ".-.";
code['s'] = "...";
code['t'] = "-";
code['u'] = "..-";
code['v'] = "...-";
code['w'] = ".--";
code['x'] = "-..-";
code['y'] = "-.--";
code['z'] = "--..";
}
void loop() {
// Morse something
morse("SOS We are sinking");
delay(5000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment