// Arduino Morse Code Transmitter - ozandamci.com
const int buttonPin = 2;
const int buzzerPin = 8;
const int ledPin = 12;
const int unit = 200; // length of one dot (ms); make it smaller to go faster
const int frequency = 700; // sound pitch (Hz)
const char* letters[] = {
".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---",
"-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-",
"..-", "...-", ".--", "-..-", "-.--", "--.."
};
const char* digits[] = {
"-----", ".----", "..---", "...--", "....-",
".....", "-....", "--...", "---..", "----."
};
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(buzzerPin, OUTPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
Serial.println("Type your message and press Enter (letters A-Z and digits 0-9).");
}
// Sends a single dot or dash
void signal(int duration) {
digitalWrite(ledPin, HIGH);
tone(buzzerPin, frequency);
delay(duration);
digitalWrite(ledPin, LOW);
noTone(buzzerPin);
delay(unit); // 1 unit gap between signals
}
// Sends the code for one letter (e.g. "...") from start to end
void sendCode(const char* code) {
for (int i = 0; code[i] != '\0'; i++) {
if (code[i] == '.') {
signal(unit); // dot: 1 unit
} else {
signal(unit * 3); // dash: 3 units
}
}
delay(unit * 2); // 3 units gap in total between letters
}
void loop() {
// Sending by hand: light and sound are on while you hold the button
if (digitalRead(buttonPin) == LOW) {
digitalWrite(ledPin, HIGH);
tone(buzzerPin, frequency);
} else {
digitalWrite(ledPin, LOW);
noTone(buzzerPin);
}
// Send the letters coming from the Serial Monitor
if (Serial.available() > 0) {
char letter = toupper(Serial.read());
if (letter >= 'A' && letter <= 'Z') {
Serial.print(letter);
Serial.print(" ");
Serial.println(letters[letter - 'A']);
sendCode(letters[letter - 'A']);
} else if (letter >= '0' && letter <= '9') {
Serial.print(letter);
Serial.print(" ");
Serial.println(digits[letter - '0']);
sendCode(digits[letter - '0']);
} else if (letter == ' ') {
delay(unit * 4); // 7 units gap in total between words
}
}
}