Note
Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts.
Why Join?
Expert Support: Solve post-sale issues and technical challenges with help from our community and team.
Learn & Share: Exchange tips and tutorials to enhance your skills.
Exclusive Previews: Get early access to new product announcements and sneak peeks.
Special Discounts: Enjoy exclusive discounts on our newest products.
Festive Promotions and Giveaways: Take part in giveaways and holiday promotions.
π Ready to explore and create with us? Click [here] and join today!
4.4 Morse Code Generatorο
Introduction
In this project, we will create a Morse code generator using a Raspberry Pi. You can input a series of characters via the terminal, and the system will output the corresponding Morse code signals using a buzzer and an LED. This project not only demonstrates basic GPIO control but also introduces Morse code, a fascinating communication method used historically for telegraphy.
What Youβll Need
The following components are required:
COMPONENT INTRODUCTION |
PURCHASE LINK |
|---|---|
- |
|
- |
|
Raspberry Pi |
- |
Circuit Diagram
The schematic diagram is shown below:
Wiring Diagram
Build the circuit following the diagram below. Ensure correct polarity for the buzzer (the terminal with the β+β sign is the positive pole):
Running the Example
All example code used in this tutorial is available in the ai-lab-kit directory.
Follow these steps to run the example:
cd ~/ai-lab-kit/python/
sudo python3 4.4_MorseCodeGenerator.py
After running the script, you can type a message in the terminal and the system will output it as Morse code using a buzzer and an LED.
Each dot is indicated by a short beep/flash, and each dash by a longer beep/flash.
Letters are separated by a brief pause, and spaces in the message create a longer pause between words.
The program keeps waiting for new input messages and will stop safely when you press
Ctrl + C, turning off both the buzzer and the LED.
Code
Below is the Python code for this project:
#!/usr/bin/env python3
from fusion_hat.pin import Pin, Mode
import time
# Initialize Buzzer and LED to GPIO pins
BeepPin = Pin(22, mode=Mode.OUT)
ALedPin = Pin(17, mode=Mode.OUT)
# Morse code representation for characters
MORSECODE = {
'A': '01', 'B': '1000', 'C': '1010', 'D': '100', 'E': '0', 'F': '0010', 'G': '110',
'H': '0000', 'I': '00', 'J': '0111', 'K': '101', 'L': '0100', 'M': '11', 'N': '10',
'O': '111', 'P': '0110', 'Q': '1101', 'R': '010', 'S': '000', 'T': '1',
'U': '001', 'V': '0001', 'W': '011', 'X': '1001', 'Y': '1011', 'Z': '1100',
'1': '01111', '2': '00111', '3': '00011', '4': '00001', '5': '00000',
'6': '10000', '7': '11000', '8': '11100', '9': '11110', '0': '11111',
'?': '001100', '/': '10010', ',': '110011', '.': '010101', ';': '101010',
'!': '101011', '@': '011010', ':': '111000',
}
# Timing (seconds)
UNIT = 0.25 # base unit
DOT = UNIT / 2 # dot length
DASH = UNIT # dash length
INTRA_SYMBOL_GAP = UNIT / 2 # gap between dot/dash in one letter
LETTER_GAP = UNIT # gap between letters
WORD_GAP = UNIT * 2 # gap between words (space)
def on():
"""Turn on the buzzer and LED."""
BeepPin.on()
ALedPin.on()
def off():
"""Turn off the buzzer and LED."""
BeepPin.off()
ALedPin.off()
def beep(duration):
"""Beep (and flash LED) for 'duration' seconds."""
on()
time.sleep(duration)
off()
def play_symbol(symbol):
"""Play one morse symbol: '0' (dot) or '1' (dash)."""
if symbol == '0':
beep(DOT)
elif symbol == '1':
beep(DASH)
time.sleep(INTRA_SYMBOL_GAP)
def morsecode(text):
"""
Convert text to Morse code and output via buzzer+LED.
Supports spaces between words and ignores unsupported characters.
"""
for ch in text:
if ch == ' ':
# Space means word gap
time.sleep(WORD_GAP)
continue
# Skip unsupported characters instead of crashing
if ch not in MORSECODE:
continue
pattern = MORSECODE[ch]
for sym in pattern:
play_symbol(sym)
# Pause between letters
time.sleep(LETTER_GAP)
def destroy():
"""Ensure buzzer and LED are turned off."""
BeepPin.off()
ALedPin.off()
print("")
try:
while True:
code = input("Please input the messenger:").upper()
print(code)
morsecode(code)
except KeyboardInterrupt:
destroy()
This Python script converts a user-provided message into Morse code and signals it using a buzzer and LED. Hereβs how it works:
Morse Code Conversion: The script translates the input text (letters, numbers, and some special characters) into Morse code using a predefined dictionary
MORSECODE.Audio-Visual Morse Code Output:
For each dot (
0), the buzzer and LED are activated for a short duration (half of the pause time).For each dash (
1), the buzzer and LED are activated for a longer duration (equal to the pause time).
User Interaction:
Users input a message, and the system converts and emits the corresponding Morse code.
The program continuously asks for new messages until interrupted.
Graceful Exit: On
Ctrl+C, the script stops, turns off the buzzer and LED, and exits cleanly.
Understanding the Code
Components Setup:
The buzzer and LED are initialized on GPIO pins 22 and 17, respectively.
Morse Code Dictionary:
Morse code is represented using β0β for dots (short signals) and β1β for dashes (long signals). For example, βAβ is represented as β01β.
Signal Functions:
The
on()andoff()functions activate or deactivate the buzzer and LED.The
beep()function combines these to create a signal with a specified duration.
Morse Code Conversion:
The
morsecode()function processes each letter of the input message. It emits a series of signals for each character using the Morse code dictionary.Main Loop:
The program continuously prompts for user input and converts the input to Morse code signals. The loop can be terminated safely with
Ctrl+C.
Troubleshooting
Buzzer or LED Does Not Work:
Cause: Incorrect wiring or GPIO pin configuration.
Solution:
Verify the buzzer is connected to GPIO 22 and the LED to GPIO 17.
Test the buzzer and LED independently using simple GPIO control scripts.
Morse Code Output Is Inaccurate:
Cause: Input characters not in the
MORSECODEdictionary.Solution:
Ensure the input contains only supported characters (A-Z, 0-9, and select symbols).
Extend the
MORSECODEdictionary to include additional characters.
Fast or Overlapping Signals:
Cause: Inadequate timing for pauses or signal durations.
Solution: Adjust the
pausevariable in themorsecode()function for clearer signaling:pause = 0.5 # Increase pause duration for slower output
Input Not Detected:
Cause: Input issues in the runtime environment (e.g., no console).
Solution: Ensure the script is run in a terminal or environment that supports
input().
Extendable Ideas
Adjustable Speed: Allow users to set the Morse code signaling speed by inputting a custom pause value.
pause = float(input("Enter pause duration (seconds): "))
Multi-Device Output: Add another LED or buzzer to display the Morse code simultaneously on different devices.
Morse Code Logging: Log the Morse code sequence to a file for each message:
with open("morse_log.txt", "a") as log_file: log_file.write(f"{message} -> {morse_sequence}\n")
Conclusion
This project is a fun way to explore Morse code and its application using Raspberry Pi. By leveraging simple components like a buzzer and LED, you can create a system that bridges historical communication methods with modern electronics. Experiment with the code to enhance your understanding and make it your own!