这个是我几年前写的了。
ir_remote.py
import pyb
from pyb import Pin, ExtInt
default_remoter = {\
69 : {"value": "1", "longtap": False}, \
70 : {"value": "2", "longtap": False}, \
71 : {"value": "3", "longtap": False}, \
68 : {"value": "4", "longtap": False}, \
64 : {"value": "5", "longtap": False}, \
67 : {"value": "6", "longtap": False}, \
7 : {"value": "7", "longtap": False}, \
21 : {"value": "8", "longtap": False}, \
9 : {"value": "9", "longtap": False}, \
22 : {"value": "*", "longtap": False}, \
25 : {"value": "0", "longtap": False}, \
13 : {"value": "#", "longtap": False}, \
24 : {"value": "up", "longtap": True}, \
82 : {"value": "down", "longtap": True}, \
8 : {"value": "left", "longtap": True}, \
90 : {"value": "right", "longtap": True}, \
28 : {"value": "OK", "longtap": False} \
}
class IRrecv:
def __init__(self, pin, remoter = default_remoter):
self.pin = pin
self.command = None
self.hold_time = 0
self.remoter = remoter
self.ext = ExtInt(pin, ExtInt.IRQ_FALLING, Pin.PULL_NONE, self.__receive)
def read_pulse(self, value):
start = pyb.micros()
while self.pin.value() == value and pyb.elapsed_micros(start) < 50000:
pass
return pyb.elapsed_micros(start)
def read_byte(self):
data = 0
for i in range(8):
if abs(self.read_pulse(0) - 560) > 200:
return None
pulse = self.read_pulse(1)
if abs(pulse - 560 ) < 200:
pass
elif abs(pulse - 1690 ) < 300:
data = (1 << i) + data
else:
return None
return data
def __receive(self, line):
self.ext.disable()
if abs(self.read_pulse(0) - 9000 ) < 500:
pulse = self.read_pulse(1)
if abs(pulse - 2250) < 500:
if (not self.remoter) or self.remoter[self.command]["longtap"]:
self.hold_time += 1
elif abs(pulse - 4500) < 500:
custom_code = self.read_byte()
custom_code_complement = self.read_byte()
command_code = self.read_byte()
command_code_complement = self.read_byte()
if custom_code is not None and \
custom_code_complement is not None and \
command_code is not None and \
command_code_complement is not None:
if custom_code + custom_code_complement == 255 and \
command_code + command_code_complement == 255:
self.command = command_code
self.hold_time = 1
self.ext.enable()
def __read_raw_code__(self):
command = self.command
self.command = None
return(command)
def read(self):
if self.hold_time == 0:
return None
else:
key = self.remoter[self.command]["value"]
self.hold_time = 0
return key
main.py
from pyb import Pin
import time
from ir_remote import IRrecv
ir = IRrecv(Pin("P6", Pin.IN))
while(True):
key = ir.read()
if key:
print(key)
time.sleep_ms(100)