# Esp32 - Buzzer huiswerk-opgave
# Copytight by Anthony Vogelaar, Perth Scotland
# rev 0.10  2025-09-12

import	time
from	machine	import	Pin

# ======================= hardware =======================

buzzer = Pin(32, Pin.OUT, value=0)

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


class Morse:
    
    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()


morse = Morse(buzzer)
try:
    morse.outCh('s')
#	 morse.outWord('sos')
#    morse.outLine('sos sos')
#    morse.outLine('Het is mooi weer vandaag')
finally :
    morse.halt()
    