Thursday 11 August 2016

Morse Code Trainer

One thing about morse code is you need repetitive training. No better way to learn and improve your reception. So here's a thing - a MicroPython program running on the BBC micro:bbit that generates random morse letters and sounds for you to train by.

IMG 0146

The connections are simple, pin'0' and GND go to an active piezo buzzer.

Code

The code is self explanatory, for those that know Python. It was written in the "Mu" code editor which has been specifically written to support the micro:bit on all platforms.

from microbit import *
import random

# 'constants' for delays all derived from dot length
dotlength = 250
dashlength = dotlength * 3
interelement = dotlength
interletter = dotlength * 2

# images for displaying dots and dashes

dot_img = Image('00000:00000:00900:00000:00000:')
dash_img = Image('00000:00000:09990:00000:00000:')

letter = ("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")

# Dictionary
morse = {
    "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":"--.."
}

# function to convert string to pattern of dots and spaces
def EncodeMorse(message):
    m = message.upper()
    enc = ""
    for c in m:
        enc = enc + morse.get(c," ")
        if morse.get(c," ") != " ":
            enc = enc + " "
    return enc
    
# function to flash out a Morse pattern on the matrix
def FlashMorse(pattern):
   for c in pattern:
       if c == ".":
           display.show(dot_img)
           pin0.write_digital(1)
           sleep(dotlength)
           display.clear()
           pin0.write_digital(0)
           sleep(interelement)
       elif c=="-":
           display.show(dash_img)
           pin0.write_digital(1)
           sleep(dashlength)
           display.clear()
           pin0.write_digital(0)
           sleep(interelement)
       elif c==" ":
           sleep(interletter)
   return

# helper function to encode and flash in one go
def MorseCode(message):
    m = EncodeMorse(message)
    print(m)
    FlashMorse(m)
    return

while True:
    message = random.choice(letter)
    MorseCode(message)
    sleep(2000)


    
    

No comments: