// Constants
const int speakerPin = 13; // Digital pin for the speaker
int morseLED = 2; // Digital pin for the LED
// Play a dot
void Morse_PlayDot(int dotDuration) {
digitalWrite(morseLED, HIGH);
tone(speakerPin, 1000, dotDuration);
delay(dotDuration);
digitalWrite(morseLED, LOW);
noTone(speakerPin);
}
// Play a dash
void Morse_PlayDash(int dotDuration) {
digitalWrite(morseLED, HIGH);
tone(speakerPin, 1000, dotDuration * 3);
delay(dotDuration * 3);
digitalWrite(morseLED, LOW);
noTone(speakerPin);
}
// Translate text to Morse code and play it
void Morse(const String& textToMorse, int dotDuration = 200) {
// Morse code dictionary
const char* morseCodes[] = {
".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---",
"-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-",
"..-", "...-", ".--", "-..-", "-.--", "--.."
};
for (int i = 0; i < textToMorse.length(); i++) {
char ch = toLowerCase(textToMorse[i]);
if (ch == ' ') {
delay(dotDuration * 3); // Pause between words
} else if (isAlphaNumeric(ch)) {
int index = ch - 'a';
if (isDigit(ch)) {
index = ch - '0' + 26;
}
String morseCode = morseCodes[index];
for (int j = 0; j < morseCode.length(); j++) {
char symbol = morseCode[j];
if (symbol == '.') {
Morse_PlayDot(dotDuration);
} else if (symbol == '-') {
Morse_PlayDash(dotDuration);
}
delay(dotDuration); // Pause between dots and dashes
}
delay(dotDuration * 2); // Pause between letters
}
}
}
// Setup function
void setup() {
pinMode(speakerPin, OUTPUT);
Serial.begin(9600);
}
// Main loop
void loop() {
if (Serial.available() > 0) {
String input = Serial.readStringUntil('\n');
Morse(input);
}
}