Raspberry Pi Pico
Morse Code Generator
For this project, I wanted to get the Pico to flash or buzz out a message in Morse code. I wanted it to automatically generate the dot and dash patterns.

This is the Fritzing diagram for this simple circuit,

Since there needed to be some definition of the Morse code patterns, I decided to write a library to do this and save it to the Pico as morse.py.
from time import sleep_ms
from micropython import const
DOT = const(100)
DASH = const(DOT * 3)
INTERELEMENT = const(DOT)
INTERLETTER = const(DOT * 2)
volume = 2512
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":"--.."
}
# buzzer, frequency, duration
def tone(buzzer, frequency, duration):
buzzer.duty_u16(volume)
buzzer.freq(frequency)
sleep_ms(duration)
buzzer.duty_u16(0)
# buzzer, frequency - plays until stopped
def note_on(buzzer, frequency):
buzzer.duty_u16(volume)
buzzer.freq(frequency)
# stop the noise
def note_off(buzzer):
buzzer.duty_u16(0)
# 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
def FlashMorse(txt, led):
pattern = EncodeMorse(txt)
for c in pattern:
if c == ".":
led.value(1)
sleep_ms(DOT)
led.value(0)
sleep_ms(INTERELEMENT)
elif c=="-":
led.value(1)
sleep_ms(DASH)
led.value(0)
sleep_ms(INTERELEMENT)
elif c==" ":
sleep_ms(INTERLETTER)
def BuzzMorse(txt, buzzer, note):
pattern = EncodeMorse(txt)
for c in pattern:
if c == ".":
tone(buzzer, note,DOT)
sleep_ms(INTERELEMENT)
elif c=="-":
tone(buzzer, note,DASH)
sleep_ms(INTERELEMENT)
elif c==" ":
sleep_ms(INTERLETTER)
def FlashBuzzMorse(txt, led, buzzer, note):
pattern = EncodeMorse(txt)
for c in pattern:
if c == ".":
led.value(1)
note_on(buzzer, note)
sleep_ms(DOT)
note_off(buzzer)
led.value(0)
sleep_ms(INTERELEMENT)
elif c=="-":
led.value(1)
note_on(buzzer, note)
sleep_ms(DASH)
note_off(buzzer)
led.value(0)
sleep_ms(INTERELEMENT)
elif c==" ":
sleep_ms(INTERLETTER)
Here is the code I used to test the library,
from machine import PWM, Pin
from morse import FlashMorse, BuzzMorse, FlashBuzzMorse
# define LED pin
light = Pin(16, Pin.OUT)
# define buzzer pin
buzz = PWM(Pin(15))
# LED only
FlashMorse("Hello World", light)
# Buzzer only
BuzzMorse("ABCDEF", buzz, 440)
# LED and Buzzer
FlashBuzzMorse("ABCDEF", light, buzz, 440)

