// Pin for the piezo buzzer
const int buzzerPin = 9;
const int timeUnit = 100;
const int freq = 500;
const int dotTime = timeUnit * 1;
const int dashTime = timeUnit * 3;
const int letterSpace = timeUnit * 3;
const int symSpace = timeUnit * 1;
const int wordSpace = timeUnit * 7;

// Morse code representation for letters A-Z and numbers 0-9
const char* morseCode[] = {
    ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", // A-J
    "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", // K-T
    "..-", "...-", ".--", "-..-", "-.--", "--.." // U-Z
};

// Morse code for numbers 0-9
const char* morseCodeNumbers[] = {
    "-----", ".----", "..---", "...--", "....-", // 0-4
    ".....", "-....", "--...", "---..", "----." // 5-9
};

void setup() {
    Serial.begin(9600); // Start serial communication at 9600 baud
    pinMode(buzzerPin, OUTPUT); // Set buzzer pin as output
    Serial.println("Please type a message to be sent over Morse code.");
}

void loop() {
    // Check if data is available to read
    if (Serial.available()) {
        String input = Serial.readStringUntil('\n'); // Read input until newline
        translateToMorse(input); // Translate and play Morse code
    }
}

void translateToMorse(String message) {
    message.toUpperCase(); // Convert message to uppercase
    for (int i = 0; i < message.length(); i++) {
        char currentChar = message[i];
        if (currentChar >= 'A' && currentChar <= 'Z') {
            playMorse(morseCode[currentChar - 'A']); // Get Morse code for letter
        } else if (currentChar >= '0' && currentChar <= '9') {
            playMorse(morseCodeNumbers[currentChar - '0']); // Get Morse code for number
        } else if (currentChar == ' ') {
            delay(wordSpace); // Space between words
        }
        delay(letterSpace); // Space between letters
    }
}

void playMorse(const char* morse) {
    for (int i = 0; morse[i] != '\0'; i++) {
        if (morse[i] == '.') {
            tone(buzzerPin, freq); // Play dot sound
            delay(dotTime); // Dot duration
        } else if (morse[i] == '-') {
            tone(buzzerPin, freq); // Play dash sound
            delay(dashTime); // Dash duration
        }
        noTone(buzzerPin); // Stop sound
        delay(symSpace); // Space between parts of the same letter
    }
}