import machine
tx = machine.Pin(2, machine.Pin.OUT)
rx = machine.Pin(3, machine.Pin.IN, machine.Pin.PULL_DOWN)
tx.value(0)
timer = machine.Timer(-1)
tx_val = 0
rx_val = 0
step = 0
done = False
def timer_isr(t):
global step, tx_val, rx_val, done
if step == 0:
tx.value(1)
rx_val = 0
elif 1 <= step <= 8:
bit_idx = step - 1
bit = (tx_val >> bit_idx) & 1
tx.value(1 - bit)
rx_line = rx.value()
rx_bit = 1 - rx_line
rx_val |= (rx_bit << bit_idx)
elif step == 9:
tx.value(0)
elif step == 10:
tx.value(0)
elif step == 11:
tx.value(0)
t.deinit()
done = True
return
step += 1
def send_and_receive_char(char):
global tx_val, step, done
tx_val = ord(char)
step = 0
done = False
timer.init(freq=9600, mode=machine.Timer.PERIODIC, callback=timer_isr)
while not done:
pass
return chr(rx_val)
while True:
text = input()
if not text:
continue
output = ""
for c in text:
output += send_and_receive_char(c)
print("Received:", output)