Skip to content

Instantly share code, notes, and snippets.

@gustavorv86
Last active November 25, 2023 21:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gustavorv86/e61fce58c91f6d717249876f2984dd47 to your computer and use it in GitHub Desktop.
Save gustavorv86/e61fce58c91f6d717249876f2984dd47 to your computer and use it in GitHub Desktop.
Reading an infrared (IR) receiver with Python on GNU/Linux

Reading an infrared (IR) receiver with Python on GNU/Linux

Many development boards incorporate an infrared receiver, such as Orange PI, Bananapi, Libre computer, Pine64, etc.

This manual explains how to configure the infrared receiver in Linux and shows an example of how to read the infrared codes emitted by a remote control.

Configuration

Show all input devices:

cat /proc/bus/input/devices

Add all protocols (add this line to the /etc/rc.local to start at boot):

ir-keytable -c -p all

Show activated IR protocols:

cat /sys/class/rc/rc0/protocols

Testing input device:

evtest /dev/input/by-path/*.ir-event
#!/usr/bin/env python3
import struct
import time
import sys
DEV_EVENT_IR = "/dev/input/event1"
"""
struct input_event {
struct timeval time; {long int, long int}
unsigned short type;
unsigned short code;
unsigned int value;
};
"""
FORMAT = 'llHHI' # long int, long int, unsigned short, unsigned short, unsigned int
EVENT_SIZE = struct.calcsize(FORMAT)
def main():
fd_ir = open(DEV_EVENT_IR, "rb")
try:
while True:
event = fd_ir.read(EVENT_SIZE)
(tv_sec, tv_usec, evtype, code, value) = struct.unpack(FORMAT, event)
if evtype != 0 or code != 0 or value != 0:
print("{}.{}: event type {}, code {}, value {}".format(tv_sec, tv_usec, evtype, code, value))
else:
# Events with code, type and value == 0 are "separator" events
print("===========================================")
except KeyboardInterrupt:
fd_ir.close()
print("\n\nClose device.")
print("Exit.")
sys.exit(0)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment