# mPy - IR remote receiver decoder on GPIO-33
# Copyright by Anthony Vogelaar, Perth Scotland
# rev 0.10  2025-07-15  initial release

from	machine		import	Pin
import	time
from	collections	import	deque

# ============================= IrRec ================================

class IrRec:
    
    def __init__(self, pin_ir=35):
        self.count  = 0							# number of received bits
        self.data   = 0							# received bit accumulator
        self.t_last = time.ticks_us()
        self.que    = deque((), 100)
        ir_rx = Pin(pin_ir, Pin.IN, Pin.PULL_UP)
        ir_rx.irq(self.onIrq, trigger=Pin.IRQ_RISING)


    # save time of rising edge in queue
    def onIrq(self, sender):
        self.que.append(time.ticks_us())
        
        
    # decode collected rising edge times to bits
    def getKey(self):
        while(self.que):
            self.t_last, t = self.que.popleft(), self.t_last
            dt = time.ticks_diff(self.t_last, t)
            if 900 < dt < 1500:							# if '0'
                self.data   = self.data << 1
                self.count += 1
            elif 2100 < dt < 2700:						# if '1'
                self.data   = (self.data << 1) + 1
                self.count += 1
            else:										# if error
                self.data  = 0
                self.count = 1
            if self.count == 33:						# if word complete
                res = self.data
                self.data  = 0
                self.count = 0
                return res								# return decoded word
        
# ============================ test =============================

if __name__ == '__main__':
    
    def test():
        ir_rec = IrRec()
        while True:
            time.sleep_ms(10)
            if res := ir_rec.getKey():
                print(hex(res))


    test()

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