# Esp32 - Morse writer using kit FKS0001 buzzer
# Copytight by Anthony Vogelaar, Perth Scotland
# rev 0.10  2025-09-24  initial release

import	time

# ===================== MorseWriter ======================

# 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': '-----'}


class MorseWriter:
    
    def __init__(self, buzzer, words_per_minute=10):
        self.buzzer = buzzer
        self.tick   = 60000 // (50 * words_per_minute)
        
        
    def _wait(self, n):
        time.sleep_ms(n*self.tick)
            

    def _dith(self):
        self.buzzer(1); self._wait(1)
        self.buzzer(0); self._wait(1)
        

    def _dah(self):
        self.buzzer(1); self._wait(3)
        self.buzzer(0); self._wait(1)
        
        
    def _waitCh(self):
        self._wait(2)
        

    def _waitWord(self):
        self._wait(4)


    def halt(self):
        self.buzzer(0)
        
        
    def outCh(self, ch):
        ch = ch.upper()
        if not ch in morse_codes: return
        code = morse_codes[ch]
        for bit in code:
            self._dith() if bit == '.' else self._dah()
            
            
    def outWord(self, word):
        for ch in word:
            self.outCh(ch)
            self._waitCh()
            
            
    def outLine(self, line):
        for word in line.split(' '):
            self.outWord(word)
            self._waitWord()

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

if __name__ == '__main__':
    
    from	machine	import	Pin

    # send 'sos sos' once
    def test1():
#        buzzer = Pin(32, Pin.OUT, value=0)		# kit FKS0001
        buzzer = Pin(39, Pin.OUT, value=0)		# Esp32s2
        m_writer = MorseWriter(buzzer, words_per_minute=20)
        try:
#            m_writer.outLine('sos')
            m_writer.outLine('sos sos')
            time.sleep(1)
        finally :
            m_writer.halt()
    
    
    def test2():
#        buzzer = Pin(32, Pin.OUT, value=0)		# kit FKS0001
        buzzer = Pin(39, Pin.OUT, value=0)		# Esp32s2
        m_writer = MorseWriter(buzzer, words_per_minute=20)
        try:
            while True:
                m_writer.outLine('Het is mooi weer vandaag')
                time.sleep(5)
        finally :
            m_writer.halt()


    test2()

# ========================== end =============================
