# mpy - Microphone excercise. Morse reader and wirter on Kit FSK0001
#   using _thread multitasking
# Copyright by Anthony Vogelaar, Perth Scotland
# rev 0.10  2025-09-27  initial release

import	time
import	_thread			as		th
from	morse_reader	import	MorseReader
from	morse_writer	import	MorseWriter
from	machine			import	Pin, ADC

# ======================== Test3 ============================

class Main:
    
    def __init__(self):
        self.active = True
        th.start_new_thread(self.m_reader, ())
        th.start_new_thread(self.m_writer, ())
        try:
            while True:
                print('*', end='')
                time.sleep(1)
        except: self.active = False
        print('done')
        
        
    def m_reader(self):
        pin_mic     = Pin(33, Pin.IN, Pin.PULL_UP)
        adc_mic     = ADC(pin_mic, atten=ADC.ATTN_0DB)				# 0..950 mV
        mr = MorseReader(adc_mic)
        while self.active:
            w = mr.getWord()										# probably adc reding  blocks threading
            print(w)
        
        
    def m_writer(self):
        buzzer = Pin(32, Pin.OUT, value=0)		
        mw = MorseWriter(buzzer, words_per_minute=20)
        t_last = time.time()
        while self.active:
            if time.time() - t_last >= 5:
                t_last = time.time()
                mw.outLine('sos')
                time.sleep_ms(1)
#                mw.outLine('Het is mooi weer vandaag')
        mw.halt()
 
# =========================== main ===============================

# Main()

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

# conclusion:
# task is active during two mSec out of 10
# when buzzer active no microphone detection


class Test:
    
    def __init__(self):
        self.active = True
        th.start_new_thread(self.task1, ())
        th.start_new_thread(self.task2, ())
        try:
            while True:
                time.sleep(1)
                print('*', end='')				# task #3
        finally:
            self.active = False
            print('\ndone')
        
        
    def task1(self):
        led = Pin(18, Pin.OUT)
        while(self.active):
            print('!', end='')
            led.toggle()
        

    def task2(self):
        led = Pin(19, Pin.OUT)
        while(self.active):
            led.toggle()
  
  
Test()

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