from machine import Pin, PWM
import time


#ir_led = PWM(Pin("GP18"))
ir_led = PWM(Pin(6))
ir_led.freq(38000)
ir_led.duty_u16(0)

READ_DELAY_US = 10000
PROCESS_DELAY_US = 30000
# so a single frame takes roughly 200ms


def emit_pulse(duration_us):
    ir_led.duty_u16(32768)  # 50% duty cycle
    time.sleep_us(duration_us)
    ir_led.duty_u16(0)      # 0% duty cycle

def xmit_bin(msg_data_bin, msg_len, repeat=1):
    msg_data_bin = (msg_data_bin << 1) + 1
    msg_len += 1

    for n in range(repeat):
        emit_pulse(4500)
        time.sleep_us(PROCESS_DELAY_US)

        for i in range(msg_len-1, -1, -1):
            if(msg_data_bin & (1<<i)):
                emit_pulse(1500)
            else:
                emit_pulse(500)

            time.sleep_us(READ_DELAY_US)

        emit_pulse(4500)
        time.sleep_us(PROCESS_DELAY_US)

def xmit_fx(id_effect, id_colour_fg, id_colour_bg, repeat=1):
    msg = id_effect
    msg = (msg << 4) + id_colour_fg
    msg = (msg << 4) + id_colour_bg
    msg = (msg << 2) + 0 # TODO: CRC

    #print(bin(msg))
    xmit_bin(msg, 14, repeat)
    #xmit_bin(0b10101010111101, 14, repeat)


try:
    while True:
        #xmit_bin(0b010101, 6)
        #xmit_bin(7774, 16, 1)
        xmit_fx(0, 6, 0, repeat=1)
        time.sleep_ms(1000)

        #xmit_bin(15964, 16, 1)
        xmit_fx(8, 2, 0, repeat=1)
        time.sleep_ms(3000)

except KeyboardInterrupt:
    ir_led.deinit()
