# esp32 - RMT and buzzer to generate morse code on pin 32
# Copytight by Anthony Vogelaar, Perth Scotland
# rev 0.10  2025-09-29

import	time
from	machine	import	Pin
from	esp32	import	RMT

# Implemented:
# MorseWriter(pin_nr=32)
#    MorseWriter.outLine(line)

# ========================= Morse ========================

# dictionary with morse codes
morse_codes = {
    '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': '--..',
    '1': '.----',	'2': '..---',	'3': '...--',	'4': '....-',
    '5': '.....',	'6': '-....',	'7': '--...',	'8': '---..',
    '9': '----.',	'0': '-----'}


# write morse code @ 10 words per minute
class MorseWriter:
    
    def __init__(self, pin_nr=32):
        self.pin_nr = pin_nr
        self.buzzer = RMT(0, pin=pin_nr, clock_div=250)		# RMT clock is 320 kHz = 3.125 uSec
        self.tick   = 25_600								# 80 mSec for 10 words per minute
        
        
    def _dith(self, data):
        data += [1, 0]
        

    def _dah(self, data):
        data += [1, 1, 1, 0]
        
        
    def _waitCh(self, data):
        data += [0, 0]
        

    def _waitWord(self, data):
        data += [0, 0, 0, 0]


    def _addCh(self, ch, data):
        ch = ch.upper()
        if ch in morse_codes:
            code = morse_codes[ch]
            for bit in code:
                self._dith(data) if bit == '.' else self._dah(data)
            

    def _addWord(self, word, data):
        for ch in word:
            self._addCh(ch, data)
            self._waitCh(data)
            
            
    def outLine(self, line):
        data = []
        for word in line.split(' '):
            self._addWord(word, data)
            self._waitWord(data)
        self.buzzer.write_pulses(self.tick, data)

# ========================== test ===========================

if __name__ == '__main__':
    
    def  test1():
        morse = MorseWriter()
        morse.outLine('sos sos')
#    	morse.outLine('Het is mooi weer vandaag')


    test1()
    
# ========================== end ============================
