Advertisement
DrAungWinHtut

MorseCodeComplete.ino

Nov 23rd, 2024
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <string.h>
  2.  
  3. // Morse code dictionary for ASCII characters (A-Z, 0-9, space, slash)
  4. const char* morseTable[38] = {
  5.   ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---",
  6.   "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-",
  7.   "..-", "...-", ".--", "-..-", "-.--", "--..", // A-Z
  8.   "-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.", // 0-9
  9.   " ", "/" // Space and slash
  10. };
  11.  
  12. void setup() {
  13.   pinMode(13, OUTPUT);
  14.   Serial.begin(9600); // Initialize serial communication
  15. }
  16.  
  17. void loop() {
  18.   if (Serial.available() > 0) {
  19.     char input[100];
  20.     int i = 0;
  21.  
  22.     // Read the ASCII text from serial
  23.     while (Serial.available() > 0 && i < 99) {
  24.       input[i] = Serial.read();
  25.       i++;
  26.       delay(10); // Delay to ensure proper input capture
  27.     }
  28.     input[i] = '\0'; // Null-terminate the string
  29.  
  30.     // Process each character and flash its Morse code
  31.     for (int j = 0; input[j] != '\0'; j++) {
  32.       flashMorse(input[j]);
  33.     }
  34.   }
  35. }
  36.  
  37. // Function to find Morse code for a character
  38. const char* getMorse(char c) {
  39.   if (c >= 'A' && c <= 'Z') {
  40.     return morseTable[c - 'A']; // Map uppercase letters
  41.   } else if (c >= 'a' && c <= 'z') {
  42.     return morseTable[c - 'a']; // Map lowercase letters
  43.   } else if (c >= '0' && c <= '9') {
  44.     return morseTable[c - '0' + 26]; // Map digits 0-9
  45.   } else if (c == ' ') {
  46.     return morseTable[36]; // Space
  47.   } else if (c == '/') {
  48.     return morseTable[37]; // Slash
  49.   }
  50.   return ""; // Unknown characters
  51. }
  52.  
  53. // Function to flash Morse code for a character
  54. void flashMorse(char c) {
  55.   const char* morse = getMorse(c);
  56.  
  57.   // Print the character and its Morse code
  58.   Serial.print("Character: ");
  59.   Serial.print(c);
  60.   Serial.print(" -> Morse: ");
  61.   Serial.println(morse);
  62.  
  63.   for (int i = 0; morse[i] != '\0'; i++) {
  64.     if (morse[i] == '.') {
  65.       digitalWrite(13, HIGH);
  66.       delay(200); // Dot duration
  67.       digitalWrite(13, LOW);
  68.       delay(200); // Gap after dot
  69.     } else if (morse[i] == '-') {
  70.       digitalWrite(13, HIGH);
  71.       delay(600); // Dash duration
  72.       digitalWrite(13, LOW);
  73.       delay(200); // Gap after dash
  74.     }
  75.   }
  76.   delay(600); // Gap between characters
  77. }
  78.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement