User Tools

Site Tools


projects:morse_code_letters

Morse Code

Morse code1) is one of the oldest data transmission method used. It was invented by the american artist Samuel F. B. Morse and used for the telegraph.

The code been modified since it's original version, so we will use International standard.

Projects

We will build three projects:

You will find the projects as new templates in Wyliodrin

What we need?

  • 1 breadboard
  • 3 LEDs
  • 3 resistors (~200 Ohm)
  • 7 jumper wires
  • 1 development board (Raspberry Pi)

Physics review

Please read the Leds page for understanding how a LED should be powered up.

This project aims to signal a letter's morse code. The program will receive a letter and will blink a LED with the letter's morse code representation.

As stated before, morse code is composed out of points and lines. For our project, a point will mean lighting up the LED for one unit of time (UNIT) and a line will mean lighting it up for three units (3*UNIT).

Wire the components

Let's connect the components to the Raspberry Pi!

We will connect one of the the ground pins (GND) of the board to the breadboard's blue line using a black cable (the color of the cable is just a preference, you may use any color you like).
All the points on the breadboard along the blue line will be now connected to the board's ground. Next
we will place a yellow LED on the breadboard and connect it's the cathode(-) to the blue line of the breadboard,
using a black jumper wire. This way the cathode will be connected to the board's ground.

The LED's anode(+) will be connected to the board's pin 2 using a resistor and a yellow cable. This way, writing
the value 1 on the pin will light up the LED and writing 0 on the pin will turn it off.

Here you can see more informations about Raspberry Pi's pins.

For a simple understanding, we used:

  • black cables to connect the ground
  • a yellow cable to connect the yellow LED's anode(+)

Let's start coding

Start Wyliodrin and setup your board. If you have already done this, you can skip this step.

When you create a new project, you can select the Morse Code Letter program template. It already has the code you need in all program languages supported by Wyliodrin.

C/C++/Objective-C

Create a new C, C++ or Objective-C project in Wyliodrin and open the main.c, main.cpp or main.m file.

First, import the strings and wiringPi library.

#include <stdio.h> 
#include <string.h> 
#include <ctype.h> 
#include <wiringPi.h> 

Define the pins that we will use and the unit time. We will set up the pin 2 and have a unit time of 500 ms.

#define MORSE_PIN 2 
#define UNIT 500 

Then initialise the library and declare the pin mode inside the main function. We need to write a value on a pin,
so we set it up in OUTPUT mode.

wiringSetup(); 
pinMode(MORSE_PIN,OUTPUT); 

Now let's take a look at the morse code. Each letter is made out of a sequence of points and lines.
What we need to do is to write a function for signalling a point and and a function for signalling a line.
Basically the functions will do the following:

  • write 1 on the MORSE_PIN (light up)
  • wait for a UNIT or 3 * UNIT, depending whether it is a point or a line
  • write 0 on the MORSE_PIN (light off)
  • wait for a UNIT
// display a point 
void showPoint () 
{ 
    digitalWrite (MORSE_PIN, HIGH); 
    delay (UNIT); 
    digitalWrite (MORSE_PIN, LOW); 
    delay (UNIT); 
} 
 
// display a line 
void showLine () 
{ 
    digitalWrite (MORSE_PIN, HIGH); 
    delay (3*UNIT); 
    digitalWrite (MORSE_PIN, LOW); 
    delay (UNIT); 
} 

Once we have the functions for signalling points and lines, we need a function for displaying a letter.
We need to store each letter's representation in a table. One of the methods is to declare an array of strings,
each position of the array memorising one letter.

const char  *LETTERS[]={ 
        ".-",       // A 
        "-...",     // B 
        "-.-.",     // C 
        "-..",      // D 
        ".",        // E 
        "..-.",     // F 
        "--.",      // G 
        "....",     // H 
        "..",       // I 
        ".---",     // J 
        "-.-",      // K 
        ".-..",     // L 
        "--",       // M 
        "-.",       // N 
        "---",      // O 
        ".--.",     // P 
        "--.-",     // Q 
        ".-.",      // R 
        "...",      // S 
        "-",        // T 
        "..-",      // U 
        "...-",     // V 
        ".--",      // W 
        "-..-",     // X 
        "-.--",     // Y 
        "--.."      // Z 
}; 

Having the arrays, all we need to do is to write the letter signalling function. This will do the following:

  • receive a letter as parameter
  • search up the table for the letter's signal string
  • for each symbol in the string, call the respective function

Searching the table for the letter's string can be done very fast. Remember that each character is stored using
it's ASCII code. Subtracting two letters will be a number. If we subtract from the letter
we wish to search the letter A, we will get the number of letters between the letter and A. This is what
we will use to search in the table.

int letterPosition = l = 'A'; 

As morse code makes no difference between upper case and lower case letters, we will change all the letters to upper case.

int getLetterIndex (char v) 
{ 
    // we convert the charater to upper case 
    // and then subtract the first letter from it 
    // for instance, if v is B, its ASCII code is 66 
    // the ASCII code for A is 65, so 'B' - 'A' is 1 
    return toupper(v)-'A'; 
} 

We need to write the signalling function. it will receive a string with the morse code, loop over it and
call the point or line functions. After that, it will wait for a three times UNIT period of time, the space
between letters.

// show the morse code for a symbol 
void showMorseCode (const char *code) 
{ 
    int i; 
    for (i=0; i<strlen (code); i++) 
    { 
        // show a point or a line 
        if (code[i]=='.') showPoint (); 
        else if (code[i]=='-') showLine (); 
    } 
    // wait three UNITs between signals 
    delay (3*UNIT); 
} 

To start the program, we need to write the main function.

int main () 
{ 
    // the letter we want to signal 
    char l = 'P'; 
    // initialize the library 
    wiringPiSetup (); 
    // set the MORSE_PIN mode to output 
    pinMode (MORSE_PIN, OUTPUT); 
    showMorseCode (LETTERS[getLetterIndex(l)]); 
    return 0; 
} 

That's all! Now press Run and select your board. You made a morse code letter! Congrats!

Pascal

Create a new Pascal project in Wyliodrin and open the main.pas.

Pascal code is similar to C, with the exception that arrays can have character indexes.

First, import the wiringPi library.

uses wiringpi; 

Define the pins that we will use and the unit time. We will set up the pin 2 and have a unit time of 500 ms.

const  
    MORSE_PIN = 2; 
    WAIT_UNIT = 500;  

Then initialise the library and declare the pin mode inside the main function. We need to write a value on a pin,
so we set it up in OUTPUT mode.

wiringSetup; 
pinMode(MORSE_PIN,OUTPUT); 

Now let's take a look at the morse code. Each letter is made out of a sequence of points and lines.
What we need to do is to write a function for signalling a point and and a function for signalling a line.
Basically the functions will do the following:

  • write 1 on the MORSE_PIN (light up)
  • wait for a WAIT_UNIT or 3 * UNIT, depending whether it is a point or a line
  • write 0 on the MORSE_PIN (light off)
  • wait for a WAIT_UNIT
// display a point  
procedure showPoint; 
begin 
    digitalWrite (MORSE_PIN, HIGH);  
    delay (WAIT_UNIT);  
    digitalWrite (MORSE_PIN, LOW);  
    delay (WAIT_UNIT);  
end; 
 
// display a line  
procedure showLine; 
begin 
    digitalWrite (MORSE_PIN, HIGH);  
    delay (3*WAIT_UNIT);  
    digitalWrite (MORSE_PIN, LOW);  
    delay (WAIT_UNIT);  
end;  

Once we have the functions for signalling points and lines, we need a function for displaying a letter.
We need to store each letter's representation in a table. One of the methods is to declare an array of strings.

const LETTERS:array ['A'..'Z'] of string = (  
        '.-',       // A  
        '-...',     // B  
        '-.-.',     // C  
        '-..',      // D  
        '.',        // E  
        '..-.',     // F  
        '--.',      // G  
        '....',     // H  
        '..',       // I  
        '.---',     // J  
        '-.-',      // K  
        '.-..',     // L  
        '--',       // M  
        '-.',       // N  
        '---',      // O  
        '.--.',     // P  
        '--.-',     // Q  
        '.-.',      // R  
        '...',      // S  
        '-',        // T  
        '..-',      // U  
        '...-',     // V  
        '.--',      // W  
        '-..-',     // X  
        '-.--',     // Y  
        '--..'      // Z  
);  

Having the arrays, all we need to do is to write the letter signalling function. This will do the following:

  • receive a letter as parameter
  • search up the table for the letter's signal string
  • for each symbol in the string, call the respective function

We need to write the signalling function. it will receive a string with the morse code, loop over it and
call the point or line functions. After that, it will wait for a three times UNIT period of time, the space
between letters.

// show the morse code for a symbol  
procedure showMorseCode (code:string) ; 
var 
    i:integer; 
begin 
    for i:=0 to length (code) do  
    begin 
        // show a point or a line  
        if code[i]='.' then showPoint 
        else if code[i]='-' then showLine;  
    end; 
    // wait three UNITs between signals  
    delay (3*WAIT_UNIT);  
end; 

To start the program, we need to write the program.

var 
    l:char; 
 
begin  
    // the letter we want to signal  
    l := 'P';  
    // initialize the library  
    wiringPiSetup;  
    // set the MORSE_PIN mode to output  
    pinMode (MORSE_PIN, OUTPUT);  
    // show the letter and the code 
    writeln (l, ' ', LETTERS[upcase(l)]); 
    // morse code the letter 
    showMorseCode (LETTERS[upcase(l)]);  
end. 

That's all! Now press Run and select your board. You made a morse code letter! Congrats!

Python

Create a new Python project in Wyliodrin and open the main.pas.

First, import the wiringPi library.

from wiringpi2 import * 

Define the pins that we will use and the unit time. We will set up the pin 2 and have a unit time of 500 ms.

MORSE_PIN =  
UNIT = 500;  

Now let's take a look at the morse code. Each letter is made out of a sequence of points and lines.
What we need to do is to write a function for signalling a point and and a function for signalling a line.
Basically the functions will do the following:

  • write 1 on the MORSE_PIN (light up)
  • wait for a WAIT_UNIT or 3 * UNIT, depending whether it is a point or a line
  • write 0 on the MORSE_PIN (light off)
  • wait for a WAIT_UNIT
# display a point  
def showPoint(): 
    digitalWrite (MORSE_PIN, 1) 
    delay (UNIT) 
    digitalWrite (MORSE_PIN, 0) 
    delay (UNIT) 
 
# display a line  
def showLine(): 
    digitalWrite (MORSE_PIN, 1) 
    delay (3*UNIT) 
    digitalWrite (MORSE_PIN, 0) 
    delay (UNIT)  

Once we have the functions for signalling points and lines, we need a function for displaying a letter.
We need to store each letter's representation in a table. One of the methods is to declare an array of strings.

LETTERS = { 
    'A': '.-',        
    'B': '-...',      
    'C': '-.-.',      
    'D': '-..',       
    'E': '.',         
    'F': '..-.',      
    'G': '--.',       
    'H': '....',      
    'I': '..',        
    'J': '.---',      
    'K': '-.-',      
    'L': '.-..',      
    'M': '--',        
    'N': '-.',        
    'O': '---',       
    'P': '.--.',      
    'Q': '--.-',      
    'R': '.-.',       
    'S': '...',       
    'T': '-',         
    'U': '..-',       
    'V': '...-',      
    'W': '.--',       
    'X': '-..-',      
    'Y': '-.--',      
    'Z': '--..'       
    } 

Having the arrays, all we need to do is to write the letter signalling function. This will do the following:

  • receive a letter as parameter
  • search up the table for the letter's signal string
  • for each symbol in the string, call the respective function

We need to write the signalling function. it will receive a string with the morse code, loop over it and
call the point or line functions. After that, it will wait for a three times UNIT period of time, the space
between letters.

// show the morse code for a symbol  
void showMorseCode (const char *code)  
{  
    int i;  
    for (i=0; i<strlen (code); i++)  
    {  
        // show a point or a line  
        if (code[i]=='.') showPoint ();  
        else if (code[i]=='-') showLine ();  
    }  
    // wait three UNITs between signals  
    delay (3*UNIT);  
} 

To start the program, we need to write the program.

def main(): 
    # the letter we want to signal  
    l = 'P';  
    # initialize the library  
    wiringPiSetup()  
    # set the MORSE_PIN mode to output  
    pinMode (MORSE_PIN, 1) 
    # show the letter and the code 
    print ("%c %s\n" % (l, LETTERS[l.upper()])); 
    # morse code the letter 
    showMorseCode (LETTERS[l.upper()]);  
 
if __name__ == "__main__": 
	main() 

PHP

Create a new Python project in Wyliodrin and open the main.pas.

PHP code is similar to C, with the exception that arrays can have character indexes. Please read the C tutorial
and view the source code here.

<?php 
define ("MORSE_PIN", 2);  
define ("UNIT", 500);  
 
$LETTERS = array ( 
    'A' => '.-',        
    'B' => '-...',      
    'C' => '-.-.',      
    'D' => '-..',       
    'E' => '.',         
    'F' => '..-.',      
    'G' => '--.',       
    'H' => '....',      
    'I' => '..',        
    'J' => '.---',      
    'K' => '-.-',      
    'L' => '.-..',      
    'M' => '--',        
    'N' => '-.',        
    'O' => '---',       
    'P' => '.--.',      
    'Q' => '--.-',      
    'R' => '.-.',       
    'S' => '...',       
    'T' => '-',         
    'U' => '..-',       
    'V' => '...-',      
    'W' => '.--',       
    'X' => '-..-',      
    'Y' => '-.--',      
    'Z' => '--..'       
    ); 
 
// display a point  
function showPoint ()  
{  
    digitalWrite (MORSE_PIN, 1);  
    delay (UNIT);  
    digitalWrite (MORSE_PIN, 0);  
    delay (UNIT);  
}  
 
// display a line  
function showLine ()  
{  
    digitalWrite (MORSE_PIN, 1);  
    delay (3*UNIT);  
    digitalWrite (MORSE_PIN, 0);  
    delay (UNIT);  
}  
 
// show the morse code for a symbol  
function showMorseCode ($code)  
{  
    for ($i=0; $i<strlen ($code); $i++)  
    {  
        // show a point or a line  
        if ($code[$i]=='.') showPoint ();  
        else if ($code[$i]=='-') showLine ();  
    }  
    // wait three UNITs between signals  
    delay (3*UNIT);  
} 
 
function main ()  
{  
    // PHP need to know that $LETTERS has been declared outside and is global 
    global $LETTERS; 
    // the letter we want to signal  
    $l = 'P';  
    // initialize the library  
    wiringPiSetup ();  
    // set the MORSE_PIN mode to output  
    pinMode (MORSE_PIN, 1);  
    // show the letter and the code 
    print ($l." ".$LETTERS[$l]."\n"); 
    // morse code the letter 
    showMorseCode ($LETTERS[$l]);  
    return 0; 
} 
 
main (); 
?> 

Learn Morse Code Letters

We will modify the morse code program so and make a game out of it. This will help people learn morse code.
To make it a little more interesting, we will add two LEDS: a red one and a green one.
The game will function as this:

  1. Players start at 100 points
  2. The game chooses a random letter, and signals it.
  3. the player is asked to recognise it:
    1. if he is right, he gains 3 points and we flash w green LED
    2. if he is wrong, he looses 2 points and we flash a red LED

Wiring the components

The wiring is a little different from the previous. We have moved the yellow LED anode to PIN 0. We wired
the cathodes of the red and green LEDs to the ground (the black wires are connected to the blue line on
the breadboard) and wired the anodes to pins 2 and 3 (the red and green wires).

Start coding

The code is pretty much similar to the previous example, all we need to do is to modify the main function.

When you create a new project, you can select the Learn Morse Code Letters program template. It already has the code you need in all program languages supported by Wyliodrin.

C/C++/Objective-C

For selecting at random a letter, we need to include the standard library

#include <stdlib.h> 

First we need to modify the MORSE_PIN declaration and add the right and wrong pins.

#define MORSE_PIN   0  
#define WRONG_PIN   2 
#define RIGHT_PIN   3 

We need to set them in output mode

pinMode (MORSE_PIN, OUTPUT);  
    pinMode (RIGHT_PIN, OUTPUT);  
    pinMode (WRONG_PIN, OUTPUT);  

In the main function, we declare a variable to keep the score. Also we make a loop, that does the following:

  1. Selects a random letter
  2. Displays the user's score
  3. Signals the letter
  4. Asks the user to enter the signalled letter
    1. If the user answers with ?, it signals the letter again
    2. If the user answers with a letter, it checks if it is the right one
    3. If the user answers with $, the program exists
int main ()  
{  
    // the letter we want to signal  
    char l; 
    // a string to read the command from 
    char cmd[100]; 
    // points 
    int points = 100; 
    printf ("Welcome to Learn Morse Code\n"); 
    printf ("The game will signall a letter for you and you have to guess it\n"); 
    printf ("If you are right, you get 3 points, if not, you lose 2 points\n"); 
 
    // initialize the library  
    wiringPiSetup ();  
    // set the MORSE_PIN mode to output  
    pinMode (MORSE_PIN, OUTPUT);  
    pinMode (RIGHT_PIN, OUTPUT);  
    pinMode (WRONG_PIN, OUTPUT);  
    // select a random seed (staring point) 
    srand (millis ()); 
    // loop while the user enetrs something different than $ 
    do 
    { 
        // print the score 
        printf ("Your score is: %d\n", points); 
        // choose a new random letter 
        // this is done by selecting a random number from 0 to 25 and 
        // adding it to the ASCII code of 'A' 
        l = 'A'+(rand () % 26); 
        // loop while the user enters something different than @ 
        do 
        { 
            // signal the chosen letter 
            showMorseCode (LETTERS[getLetterIndex(l)]);  
            // ask the user whar letter it was 
            printf ("What was the signalled letter? (type @ to signall it again, ? if you don't know or $ to quit)\n"); 
            // read input from the user into the variable cmd 
            fgets (cmd, 100, stdin); 
            // if the user entered @, signal the letter again 
        } while (cmd[0]=='@'); 
        if (cmd[0] != '?' && cmd[0] != '$') 
        { 
            if (toupper (cmd[0]) == l)  
            { 
                points=points+3; 
                printf ("You are right, the letter was %c %s\n", l, LETTERS[getLetterIndex(l)]); 
                // signal that the user is right 
                digitalWrite (RIGHT_PIN, HIGH); 
                delay (2*UNIT); 
                digitalWrite (RIGHT_PIN, LOW); 
            } 
            else  
            { 
                points = points - 2; 
                printf ("You are wrong, the letter was %c %s\n", l, LETTERS[getLetterIndex(l)]); 
                // signal that the user is wrong 
                digitalWrite (WRONG_PIN, HIGH); 
                delay (2*UNIT); 
                digitalWrite (WRONG_PIN, LOW); 
            } 
        } 
    } while (cmd[0] != '$'); 
    return 0; 
} 

Happy Morse Code learning!

Pascal

First we need to modify the MORSE_PIN declaration and add the right and wrong pins.

const  
    MORSE_PIN = 0; 
    WRONG_PIN = 2; 
    RIGHT_PIN = 3; 
    WAIT_UNIT = 500;  

In the main function, we declare a variable to keep the score. Also we make a loop, that does the following:

  1. Selects a random letter. This is a little tricky. We will select a random number from 0 to 25. We add this number to the ASCII code of the letter 'A', that is ord('A') and than transform the result into the corresponding character (chr(ord('A')+random(26))
  2. Displays the user's score
  3. Signals the letter
  4. Asks the user to enter the signalled letter
    1. If the user answers with ?, it signals the letter again
    2. If the user answers with a letter, it checks if it is the right one
    3. If the user answers with $, the program exists
var 
    l:char; 
    points:integer; 
    cmd: char; 
 
begin  
    // points 
    points := 100; 
    writeln ('Welcome to Learn Morse Code'); 
    writeln ('The game will signall a letter for you and you have to guess it'); 
    writeln ('If you are right, you get 3 points, if not, you lose 2 points\n'); 
 
    // initialize the library  
    wiringPiSetup;  
    // set the MORSE_PIN mode to output  
    pinMode (MORSE_PIN, OUTPUT);  
    pinMode (RIGHT_PIN, OUTPUT);  
    pinMode (WRONG_PIN, OUTPUT);  
    // select a random seed (staring point) 
    randomize; 
    // loop while the user enetrs something different than $ 
    repeat 
        // print the score 
        writeln ('Your score is: ', points); 
        // choose a new random letter 
        l := chr(ord('A')+random(26)); 
        // loop while the user enters something different than @ 
        repeat 
            // signal the chosen letter 
            showMorseCode (LETTERS[l]);  
            // ask the user whar letter it was 
            writeln ('What was the signalled letter? (type @ to signall it again, ? if you don''t know or $ to quit)'); 
            // read input from the user into the variable cmd 
            readln (cmd); 
            // if the user entered @, signal the letter again 
        until cmd <> '@'; 
        if (cmd <> '?') and (cmd <> '$') then 
        begin 
            if upcase (cmd) = l then 
            begin 
                points:=points+3; 
                writeln ('You are right, the letter was ', l, ' ', LETTERS[l]); 
                // signal that the user is right 
                digitalWrite (RIGHT_PIN, HIGH); 
                delay (2*WAIT_UNIT); 
                digitalWrite (RIGHT_PIN, LOW); 
            end 
            else  
            begin 
                points := points - 2; 
                writeln ('You are wrong, the letter was ', l, ' ',  LETTERS[l]); 
                // signal that the user is wrong 
                digitalWrite (WRONG_PIN, HIGH); 
                delay (2*WAIT_UNIT); 
                digitalWrite (WRONG_PIN, LOW); 
            end; 
        end; 
    until cmd = '$'; 
end. 

Happy Morse Code learning!

Python

We need to import the random library, so we can select random letters.

from random import * 

We need change the MORSE pin and define the WRONG and RIGHT pins

MORSE_PIN = 0 
WRONG_PIN = 2 
RIGHT_PIN = 3 
UNIT = 500 

In the main function, we declare a variable to keep the score. Also we make a loop, that does the following:

  1. Selects a random letter. This is a little tricky. We will select a random number from 0 to 25. We add this number to the ASCII code of the letter 'A', that is ord('A') and than transform the result into the corresponding character (chr(ord('A')+randint(0, 25))
  2. Displays the user's score
  3. Signals the letter
  4. Asks the user to enter the signalled letter
    1. If the user answers with ?, it signals the letter again
    2. If the user answers with a letter, it checks if it is the right one
    3. If the user answers with $, the program exists
def main(): 
    # initial score 
    points = 100 
    # command enetered by the user 
    cmd = "" 
    # initialize the library  
    wiringPiSetup()  
    # set the MORSE_PIN mode to output  
    pinMode (MORSE_PIN, 1) 
    pinMode (RIGHT_PIN, 1) 
    pinMode (WRONG_PIN, 1) 
    quit = False; 
    while not quit: 
        print ("Your score is %d\n" % points); 
        l = chr (ord('A')+ randint (0, 25)) 
        signalAgain = True 
        while signalAgain: 
            # morse code the letter 
            showMorseCode (LETTERS[l.upper()]);  
            # ask the user whar letter it was 
            cmd = raw_input ('What was the signalled letter? (type @ to signall it again, ? if you don''t know or $ to quit)'); 
            # if the user entered @, signal the letter again 
            print cmd[0] 
            if cmd[0] == '@': 
                signalAgain = True 
            else: 
                signalAgain = False 
            print signalAgain 
        if cmd[0] != '?' and cmd[0] != '$': 
            if cmd[0].upper() == l: 
                points=points+3; 
                print ('You are right, the letter was %c %s\n' % (l, LETTERS[l])); 
                # signal that the user is right 
                digitalWrite (RIGHT_PIN, HIGH); 
                delay (2*UNIT); 
                digitalWrite (RIGHT_PIN, LOW); 
            else: 
                points = points - 2; 
                print ('You are wrong, the letter was %c %s\n' % (l, LETTERS[l])); 
                # signal that the user is wrong 
                digitalWrite (WRONG_PIN, HIGH); 
                delay (2*UNIT); 
                digitalWrite (WRONG_PIN, LOW); 
        if cmd[0] == '$': 
            quit = True 
 
if __name__ == "__main__": 
    main() 

Happy Morse Code learning!

Signal a text in morse code

When you create a new project, you can select the Morse Code Message program template. It already has the code you need in all program languages supported by Wyliodrin.

The third project is reading a text from the user and signalling it. For this, we will modify a little the wiring
from the previous project. We will keep the signalling and the green LED. We will blink the green between morse
code words.

We need to complete the morse code. Up to know, we have used only letters, but morse code has numbers too. For this, we will declare in the project a new table with numbers. The project will function as follows:

  1. Ask the user to enter a message
  2. loop over each character of the message, and check if
    1. it is a letter, search it up in the letters table and show the morse code for the letter
    2. it is a number, search it up in the numbers table and show the morse code for that number
    3. if it is a space, wait for seven units of time

Let's start coding

C/C++/Objective-C

We will declare the numbers

// morse code table for numbers	        
const char *NUMBERS[]={ 
        "-----",    // 1 
        ".----",    // 2 
        "..---",    // 3 
        "...--",    // 4 
        "....-",    // 5 
        ".....",    // 6 
        "-....",    // 7 
        "--...",    // 8 
        "---..",    // 9 
        "----."     // 0 
}; 

We will add two functions to check if the character is a letter or a number

// check wether v is a letter 
int isLetter (char v) 
{ 
    v = toupper (v); 
    if (v >= 'A' && v <= 'Z') return 1; 
    else return 0; 
} 
 
// check wheter v is a number 
int isNumber (char v) 
{ 
    if (v >= '0' && v <= '9') return 1; 
    else return 0; 
} 

We will declare the pins for the signalling and the words space

// pin used to signal morse code 
#define MORSE_PIN   0 
// pin used to signal spaces between words 
#define SPACE_PIN   2 

The main function is modified to signal a message

int main () 
{ 
    int i; 
    char symbol; 
    char message[500]; 
    // initialize the library 
    wiringPiSetup (); 
 
	// set the MORSE_PIN to OUTPUT mode 
	pinMode (MORSE_PIN, OUTPUT); 
 
	// set the SPACE_PIN to OUTPUT mode 
	pinMode (SPACE_PIN, OUTPUT); 
 
	// read the message 
	printf ("Enter the message: "); 
	fgets (message, 500, stdin); 
 
	// take each charater from the message and signal it 
	for (i=0; i<strlen (message); i++) 
	{ 
	    // get a letter from the mesage 
	    symbol = message[i]; 
	    if (isLetter(symbol))  
	    { 
	        printf ("%c %s\n", symbol, LETTERS[getLetterIndex(symbol)]); 
	        showMorseCode (LETTERS[getLetterIndex(symbol)]); 
	    } 
	    else if (isNumber(symbol)) 
	    { 
	        printf ("%c %s\n", symbol, NUMBERS[getNumberIndex(symbol)]); 
	        showMorseCode (NUMBERS[getNumberIndex(symbol)]); 
	    } 
	    else if (symbol == ' ') 
	    { 
	        // a space is a 7 UNIT long wait 
	        // light up the spaces led and wait 7 UNITS 
	        printf ("\n"); 
	        digitalWrite (SPACE_PIN, HIGH); 
	        delay (7*UNIT); 
	        digitalWrite (SPACE_PIN, LOW); 
	    } 
	} 
 
	return 0; 
} 

Pascal

We will declare the numbers

// morse code table for numbers	        
const NUMBERS:array['0'..'9'] of string = ( 
        '----.',    // 0 
        '-----',    // 1 
        '.----',    // 2 
        '..---',    // 3 
        '...--',    // 4 
        '....-',    // 5 
        '.....',    // 6 
        '-....',    // 7 
        '--...',    // 8 
        '---..'     // 9 
); 

We will add two functions to check if the character is a letter or a number

// check whether v is a letter 
function isLetter (v:char):boolean; 
begin 
    v := upcase (v); 
    if (v >= 'A') and (v <= 'Z') then isLetter:=true 
    else isLetter:=false; 
end; 
 
// check whether v is a number 
function isNumber (v:char):boolean; 
begin 
    if (v >= '0') and (v <= '9') then isNumber:=true 
    else isNumber:=false; 
end; 

We will declare the pins for the signalling and the words space

const  
    // pin used to signal morse code 
    MORSE_PIN = 0; 
    // pin used to signal spaces between words 
    SPACE_PIN = 2; 
    // the unit time for a point 
    WAIT_UNIT = 500;  

The main function is modified to signal a message

var 
    i:integer; 
    symbol:char; 
    message:string; 
 
begin  
    // the letter we want to signal  
    // initialize the library  
    wiringPiSetup;  
    // set the MORSE_PIN mode to output  
    pinMode (MORSE_PIN, OUTPUT);  
    // set the SPACE_PIN to OUTPUT mode 
	pinMode (SPACE_PIN, OUTPUT); 
	// read the message 
	write ('Enter the message: '); 
	readln (message); 
	for i:=1 to length(message) do 
	begin 
	    symbol := message[i]; 
        if isLetter(symbol) then 
	    begin 
	        writeln (symbol, ' ', LETTERS[upcase(symbol)]); 
	        showMorseCode (LETTERS[upcase(symbol)]); 
	    end 
	    else if isNumber(symbol) then 
	    begin 
	        writeln (symbol, ' ', NUMBERS[symbol]); 
	        showMorseCode (NUMBERS[symbol]); 
	    end 
	    else if symbol = ' ' then 
	    begin 
	        // a space is a 7 UNIT long wait 
	        // light up the spaces led and wait 7 UNITS 
	        writeln (' '); 
	        digitalWrite (SPACE_PIN, HIGH); 
	        delay (7*WAIT_UNIT); 
	        digitalWrite (SPACE_PIN, LOW); 
	    end; 
    end; 
end. 

Python

We will declare the numbers

// morse code table for numbers	        
const char *NUMBERS[]={ 
        "-----",    // 1 
        ".----",    // 2 
        "..---",    // 3 
        "...--",    // 4 
        "....-",    // 5 
        ".....",    // 6 
        "-....",    // 7 
        "--...",    // 8 
        "---..",    // 9 
        "----."     // 0 
}; 

We will add two functions to check if the character is a letter or a number

# check whether v is a letter 
def isLetter (v): 
    v = v.upper() 
    if v >= 'A' and v <= 'Z': 
        return True 
    else: 
        return False 
 
 
# check whether v is a number 
def isNumber (v): 
    if v >= '0' and v <= '9': 
        return True 
    else: 
        return False 

We will declare the pins for the signalling and the words space

# pin used to signal morse code 
MORSE_PIN = 0 
# pin used to signal spaces between words 
SPACE_PIN = 2 

The main function is modified to signal a message

def main(): 
    # initialize the library 
    wiringPiSetup (); 
 
    # set the MORSE_PIN to OUTPUT mode 
    pinMode (MORSE_PIN, 1); 
 
    # set the SPACE_PIN to OUTPUT mode 
    pinMode (SPACE_PIN, 1); 
 
    # read the message 
    message = raw_input ("Enter a message: ") 
 
    # take each charater from the message and signal it 
    for i in range (0, len (message)): 
        # get a letter from the mesage 
        symbol = message[i]; 
        if isLetter(symbol): 
            print ("%c %s" % (symbol, LETTERS[symbol.upper()])) 
            showMorseCode (LETTERS[symbol.upper()]) 
        elif isNumber(symbol): 
            print ("%c %s" % (symbol, NUMBERS[symbol])) 
            showMorseCode (NUMBERS[symbol]) 
        elif symbol == ' ': 
            # a space is a 7 UNIT long wait 
            # light up the spaces led and wait 7 UNITS 
            print (" ") 
            digitalWrite (SPACE_PIN, 1) 
            delay (7*UNIT) 
            digitalWrite (SPACE_PIN, 0) 
 
if __name__ == "__main__": 
    main() 
1) More about Morse Code is available on http://en.wikipedia.org/wiki/Morse_code
projects/morse_code_letters.txt · Last modified: 2014/01/18 20:24 by alexandru.radovici