Morse Translator

ASCII table

ASCII (American Standard Code for Information Interchange) converts a-z to 97-122, A-Z to 65-90, 0-9 to 48-57, space to 32, final to \0 or 00. For example S O S is 83 32 79 32 83.


  // Morse code for blinking a LED
int ledPin = 13; 
int dotDelay = 200;

 // [] means array, with the name letters for the array. char is a type of variable meaning character. * is a pointer, it points to the character of the array in order
char* letters[] = {
  ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..",    // A-I
  ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.",  // J-R
  "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."          // S-Z
};

// it's a second array for numbers 0 to 9. These two arrays are arrays of arrays, also known as  an array of string literals. String literal can be named strings.
//Example of string literal: ..--- (another could be az8mhello, because a string is several character together, like a word). 
// We could think as an array of an array of characters
char* numbers[] = {
  "-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----."};

// if I write letters[0] it means .-, because it's the first element of the array letters, and letters[26] is --..
// After words .- will mean A and --.. will mean Z
void setup(){
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop(){
  char ch;
  if (Serial.available() > 0){
    ch = Serial.read();
    if (ch >= 'a' && ch <= 'z')
    {
      flashSequence(letters[ch - 'a']);
    }
    else if (ch >= 'A' && ch <= 'Z')
    {
      flashSequence(letters[ch - 'A']);
    }
    else if (ch >= '0' && ch <= '9')
    {
      flashSequence(numbers[ch - '0']);
    }
    else if (ch == ' ')
    {
      delay(dotDelay * 4);  // gap between words  
    }
  }
}

void flashSequence(char* sequence){
  int i = 0;
  while (sequence[i] != NULL)
  {
    flashDotOrDash(sequence[i]);
    i++;
  }
  delay(dotDelay * 3);    // gap between letters
}

void flashDotOrDash(char dotOrDash){
  digitalWrite(ledPin, HIGH);
  if (dotOrDash == '.')
  {
    delay(dotDelay);           
  }
  else // must be a dash
  {
    delay(dotDelay * 3);           
  }
  digitalWrite(ledPin, LOW);    
  delay(dotDelay); // gap between flashes
}