Raspberry Pi Project 2: Morse Code Generator

Using an Ultra Bright LED and a Transistor, we make a simple circuit and a Python script to transmit Morse Code messages.

The following project uses the same circuit we used in tutorial 4 to create a morse code generator.

Raspberry Pi Morse Code Generator Schematic Circuit Diagram

Open IDLE on your Raspberry Pi (Menu > Programming > Python 2 (IDLE)) and open a new project (File > New File).  Then type the following:

import RPi.GPIO as GPIO
import time
from sys import argv
timeunit=0.2
gpin=18
GPIO.setmode(GPIO.BCM)
GPIO.setup(gpin, GPIO.OUT)
GPIO.output(gpin, False)
inpmessage = argv[1]

# . = 1 unit
# - = 3unit
# 1 unit between . and _
# 3 units between letters
# 7 units between words
#def load_morsecode():
#load morse code
morse=[""]*43
morse[0]="-----"
morse[1]="*----"
morse[2]="**---"
morse[3]="***--"
morse[4]="****-"
morse[5]="*****"
morse[6]="-****"
morse[7]="--***"
morse[8]="---**"
morse[9]="----*"
morse[17]="*-"
morse[18]="-***"
morse[19]="-"
morse[20]="-**"
morse[21]="*"
morse[22]="*"
morse[23]="--*"
morse[24]="****"
morse[25]="**"
morse[26]="*---"
morse[27]="-*-"
morse[28]="*"
morse[29]="--"
morse[30]="-*"
morse[31]="---"
morse[32]="*--*"
morse[33]="--*-"
morse[34]=""
morse[35]="***"
morse[36]="-"
morse[37]="**-"
morse[38]="***-"
morse[39]="*--"
morse[40]="-**-"
morse[41]="-*--"
morse[42]="--**"


def morse_code(allchars):
        chars=allchars.split(",")
        for char in chars:
                for symbol in char:
                        print(symbol)
                        if symbol=="*":
                                GPIO.output(gpin, True)
                                time.sleep(timeunit)
                                GPIO.output(gpin, False)
                                time.sleep(timeunit)
                        if symbol=="-":
                                GPIO.output(gpin, True)
                                time.sleep(timeunit*3)
                                GPIO.output(gpin, False)
                                time.sleep(timeunit)
                        if symbol==" ":
                                GPIO.output(gpin, False)
                                time.sleep(timeunit*3) #allows for the unit used after the last symbol
                
                time.sleep(timeunit*3)

def texttomorse(inputtext):
        op=""
        for char in inputtext:
                if char==" ":
                        op=op+" ,"
                else:
                        op=op+morse[ord(char)-48]+","
        return op

message=inpmessage
message=message.upper()

print(message)
morse=texttomorse(message)
print(morse)
morse_code(morse)

Save your project as morsecode.py (File > Save As) in your Documents folder.

Now open Terminal (Menu > Accessories > Terminal) and type the following command, along with a message:

python morsecode.py "hello world"