{"id":396,"date":"2021-02-07T15:02:39","date_gmt":"2021-02-07T15:02:39","guid":{"rendered":"https:\/\/samndave.org.uk\/ourdoc\/?p=396"},"modified":"2025-07-10T16:11:34","modified_gmt":"2025-07-10T16:11:34","slug":"raspberry-pi-ir-remote-and-python","status":"publish","type":"post","link":"https:\/\/samndave.org.uk\/index.php\/2021\/02\/07\/raspberry-pi-ir-remote-and-python\/","title":{"rendered":"Raspberry Pi: IR Remote and Python"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Small infrared remotes are a cheap way to add a level of remote control to a Raspberry Pi project. The one pictured below was under \u00a35 (from Everything Pi) for the remote and IR receiver module. As the other code I was working on was in python, I also wanted a python program which could detect and respond to the remote. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The following is based on Raspian Buster. From Raspian Stretch, support for the traditional IR handler, LIRC was dropped in favour of ir-keytable. I found documentation on how to use this with python hard to come by, hopefully this article will help others finding the same.<\/p>\n\n\n\n<div class=\"wp-block-image is-style-default\"><figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"406\" height=\"518\" src=\"http:\/\/samndave.org.uk\/wp-content\/uploads\/2021\/02\/IR_remote.jpg\" alt=\"\" class=\"wp-image-402\" srcset=\"https:\/\/samndave.org.uk\/wp-content\/uploads\/2021\/02\/IR_remote.jpg 406w, https:\/\/samndave.org.uk\/wp-content\/uploads\/2021\/02\/IR_remote-235x300.jpg 235w\" sizes=\"auto, (max-width: 406px) 100vw, 406px\" \/><\/figure><\/div>\n\n\n\n<h3 class=\"wp-block-heading\">Wiring it up<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The wiring connections are fairly simple. The receiver module had two pins marked + and -, connect these to the 3.3v output and GND. The other pin is for data, I connected this to GPIO 18, pin 12.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The remote requires a CR2025 battery, I didn&#8217;t have one but a CR2032 works fine.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Once connected, point the remote and the sensor and if it detects a signal, a small LED on the module flashes. Another way to test if the remote is working is to look at the end of the remote with a camera, it should detect the flash.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">ir-keytable configuration<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">To start using ir-keytable, a device has to be configured. As root, edit \/boot\/config.txt and uncomment the line below, ensuring you have the correct pin set, and reboot.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>dtoverlay=gpio-ir,gpio_pin=18<\/code><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Install the ir-keytable package:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>sudo apt install ir-keytable<\/code><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">There are a number of well known remote definition files in <code>\/lib\/udev\/rc_keymaps<\/code>, however knowing what to look for in an unbranded cheap remote like mine is not easy. Creating a custom keymap is probably the easiest way forward.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To test input run:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>sudo ir-keytable -v -t -p all<\/code><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This should report it has found an input device (possibly <code>\/dev\/input\/event0<\/code>) and list currently supported protocols. Begin pressing data on your remote and you should see events fill the screen, a key down and key up for each press:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Testing events. Please, press CTRL-C to abort.\n54703.160065: lirc protocol(nec): scancode = 0x40\n54703.160094: event type EV_MSC(0x04): scancode = 0x40\n54703.160094: event type EV_KEY(0x01) key_down:(0x0006)\n54703.160094: event type EV_SYN(0x00).\n54703.220082: lirc protocol(nec): scancode = 0x40 repeat\n54703.220110: event type EV_MSC(0x04): scancode = 0x40\n54703.220110: event type EV_SYN(0x00).\n54703.340030: event type EV_KEY(0x01) key_up: (0x0006)\n54703.340030: event type EV_SYN(0x00).<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In this case I pressed the number 5 key, which I can see has the code 0x40. I can also see it is using the nec protocol. Look at one of the examples in <code>\/lib\/dev\/rc_keymaps<\/code> for an idea of the keymap file. Open a blank text document, give your remote a name then using the ir-keymap test above, run through and press each button, assigning it to an event code, to build a keymap file like below.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">I called my remote ultraThin as this is how it was advertised when sold. For a list of valid event codes, see the kernel header file at <a href=\"https:\/\/github.com\/torvalds\/linux\/blob\/master\/include\/uapi\/linux\/input-event-codes.h\">https:\/\/github.com\/torvalds\/linux\/blob\/master\/include\/uapi\/linux\/input-event-codes.h<\/a><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;&#91;protocols]]\nname = \"UltraThin\"\nprotocol = \"nec\"\nvarient = \"nec32\"\n\n&#91;protocols.scancodes]\n0x45 = \"KEY_1\"\n0x46 = \"KEY_2\"\n0x47 = \"KEY_3\"\n0x44 = \"KEY_4\"\n0x40 = \"KEY_5\"\n0x43 = \"KEY_6\"\n0x07 = \"KEY_7\"\n0x15 = \"KEY_8\"\n0x09 = \"KEY_9\"\n0x16 = \"KEY_NUMERIC_STAR\"\n0x19 = \"KEY_0\"\n0x0d = \"KEY_NUMERIC_POUND\"\n0x18 = \"KEY_UP\"\n0x08 = \"KEY_LEFT\"\n0x1c = \"KEY_OK\"\n0x5a = \"KEY_RIGHT\"\n0x52 = \"KEY_DOWN\"<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">We can test the file by flushing any configuration, ensuring our configuration is fully listed and running the test again. Below flushes the configuration, loads our file followed by me pressing 7, * and the right arrow (sudo -s is considered bad practice but makes life easier):<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>astroberry@astropi:\/tmp $ sudo -s\nroot@astropi:\/tmp# ir-keytable -c\nOld keytable cleared\nroot@astropi:\/tmp# ir-keytable -w ultraThin.toml \nWrote 17 keycode(s) to driver\nProtocols changed to nec \nroot@astropi:\/tmp# ir-keytable -r\nscancode 0x0007 = KEY_7 (0x08)\nscancode 0x0008 = KEY_LEFT (0x69)\nscancode 0x0009 = KEY_9 (0x0a)\nscancode 0x000d = KEY_NUMERIC_POUND (0x20b)\nscancode 0x0015 = KEY_8 (0x09)\nscancode 0x0016 = KEY_NUMERIC_STAR (0x20a)\nscancode 0x0018 = KEY_UP (0x67)\nscancode 0x0019 = KEY_0 (0x0b)\nscancode 0x001c = KEY_OK (0x160)\nscancode 0x0040 = KEY_5 (0x06)\nscancode 0x0043 = KEY_6 (0x07)\nscancode 0x0044 = KEY_4 (0x05)\nscancode 0x0045 = KEY_1 (0x02)\nscancode 0x0046 = KEY_2 (0x03)\nscancode 0x0047 = KEY_3 (0x04)\nscancode 0x0052 = KEY_DOWN (0x6c)\nscancode 0x005a = KEY_RIGHT (0x6a)\nEnabled kernel protocols: lirc nec \nroot@astropi:\/tmp# ir-keytable -t\nTesting events. Please, press CTRL-C to abort.\n55313.370128: lirc protocol(nec): scancode = 0x7\n55313.370152: event type EV_MSC(0x04): scancode = 0x07\n55313.370152: event type EV_KEY(0x01) key_down: KEY_7(0x0008)\n55313.370152: event type EV_SYN(0x00).\n55313.440052: lirc protocol(nec): scancode = 0x7 repeat\n55313.440076: event type EV_MSC(0x04): scancode = 0x07\n55313.440076: event type EV_SYN(0x00).\n55313.560035: event type EV_KEY(0x01) key_up: KEY_7(0x0008)\n55313.560035: event type EV_SYN(0x00).\n55314.510051: lirc protocol(nec): scancode = 0x16\n55314.510076: event type EV_MSC(0x04): scancode = 0x16\n55314.510076: event type EV_KEY(0x01) key_down: KEY_NUMERIC_STAR(0x020a)\n55314.510076: event type EV_SYN(0x00).\n55314.560050: lirc protocol(nec): scancode = 0x16 repeat\n55314.560071: event type EV_MSC(0x04): scancode = 0x16\n55314.560071: event type EV_SYN(0x00).\n55314.680031: event type EV_KEY(0x01) key_up: KEY_NUMERIC_STAR(0x020a)\n55314.680031: event type EV_SYN(0x00).\n55316.900134: lirc protocol(nec): scancode = 0x5a\n55316.900162: event type EV_MSC(0x04): scancode = 0x5a\n55316.900162: event type EV_KEY(0x01) key_down: KEY_RIGHT(0x006a)\n55316.900162: event type EV_SYN(0x00).\n55316.970052: lirc protocol(nec): scancode = 0x5a repeat\n55316.970077: event type EV_MSC(0x04): scancode = 0x5a\n55316.970077: event type EV_SYN(0x00).\n55317.060081: lirc protocol(nec): scancode = 0x5a repeat\n55317.060106: event type EV_MSC(0x04): scancode = 0x5a\n55317.060106: event type EV_SYN(0x00).\n55317.180032: event type EV_KEY(0x01) key_up: KEY_RIGHT(0x006a)\n55317.180032: event type EV_SYN(0x00).\n^C\nroot@astropi:\/tmp# exit\nexit\nastroberry@astropi:\/tmp $ <\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Now we know this works, we can make a permanent change.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>cp ultraThin.toml \/etc\/rc_keymaps\nvi \/etc\/rc_maps.cfg\n  #driver table                    file\n  *       *                        ultraThin.toml\n  *       rc-adstech-dvb-t-pci     adstech_dvb_t_pci.toml\nvi \/etc\/rc.local\n# add the following line\n\/usr\/bin\/ir-keytable -a \/etc\/rc_maps.cfg -s rc0<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">On reboot, try <code>ir-keytable -t<\/code> again and you should see your key codes listed on a button press. This will now feed events into the standard linux event system, which means you can use event handling libraries from any language you wish to use. Test this by installing and running evtest. Remember we noted the input device earlier, now is the time to use it.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ sudo apt install evtest\n$ evtest \/dev\/input\/event0\nInput driver version is 1.0.1\nInput device ID: bus 0x19 vendor 0x1 product 0x1 version 0x100\nInput device name: \"gpio_ir_recv\"\nSupported events:\n  Event type 0 (EV_SYN)\n  Event type 1 (EV_KEY)\n    Event code 2 (KEY_1)\n    Event code 3 (KEY_2)\n    Event code 4 (KEY_3)\n... output cut ...\nTesting ... (interrupt to exit)\nEvent: time 1612701161.123493, type 4 (EV_MSC), code 4 (MSC_SCAN), value 19\nEvent: time 1612701161.123493, type 1 (EV_KEY), code 11 (KEY_0), value 1\nEvent: time 1612701161.123493, -------------- SYN_REPORT ------------\nEvent: time 1612701161.173486, type 4 (EV_MSC), code 4 (MSC_SCAN), value 19\nEvent: time 1612701161.173486, -------------- SYN_REPORT ------------\nEvent: time 1612701161.293459, type 1 (EV_KEY), code 11 (KEY_0), value 0\nEvent: time 1612701161.293459, -------------- SYN_REPORT ------------\nEvent: time 1612701162.103503, type 4 (EV_MSC), code 4 (MSC_SCAN), value 52\nEvent: time 1612701162.103503, type 1 (EV_KEY), code 108 (KEY_DOWN), value 1\nEvent: time 1612701162.103503, -------------- SYN_REPORT ------------\nEvent: time 1612701162.153497, type 4 (EV_MSC), code 4 (MSC_SCAN), value 52\nEvent: time 1612701162.153497, -------------- SYN_REPORT ------------\nEvent: time 1612701162.273457, type 1 (EV_KEY), code 108 (KEY_DOWN), value 0\nEvent: time 1612701162.273457, -------------- SYN_REPORT ------------<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">A key press of 0 and down has been successfully detected.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Using events for IR remotes in python<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">To read events, python needs the evdev package:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>apt install python3-evdev<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">There is a tutorial about using the event system at <a href=\"https:\/\/python-evdev.readthedocs.io\/en\/latest\/tutorial.html\">https:\/\/python-evdev.readthedocs.io\/en\/latest\/tutorial.html<\/a>. First we can use list_devices() to locate all input devices on the system we can use. We loop through to find one called gpio_ir_recv, which it is the IR receiver.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">After that we can use read_loop to read all events. In the code below there are two ways demonstrated of reading the events. Another consideration is writing a function to return data.keycode as a string of a key pressed, or a blank string if nothing is pressed.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># IR remote tester\n# Assumes device already configured with ir-keytable\n\nfrom evdev import *\n\ndevices = &#91;InputDevice(path) for path in list_devices()]\n# Define IR input\nirin = None\nfor device in devices:\n    #print(device.path, device.name, device.phys)\n    if(device.name==\"gpio_ir_recv\"):\n        irin = device\n\nif(irin == None):\n    print(\"Unable to find IR input device, exiting\")\n    exit(1)\n\nprint(\"IR input device found at\", irin.path)\n\n# Read events and return string\ndef readInputEvent(device):\n    for event in device.read_loop():\n        # Event returns sec, usec (combined with .), type, code, value\n        # Type 01 or ecodes.EV_KEY is a keypress event\n        # a value of  0 is key up, 1 is key down\n        # the code is the value of the keypress\n        # Full details at https:\/\/python-evdev.readthedocs.io\/en\/latest\/apidoc.html\n\n        # However we can use the categorize structure to simplify things\n        # .keycode - Text respresentation of the key\n        # .keystate - State of the key, may match .key_down or .key_up\n        # See https:\/\/python-evdev.readthedocs.io\/en\/latest\/apidoc.html#evdev.events.InputEvent\n        if event.type == ecodes.EV_KEY:\n            print(\"Event received\")\n            # Alert about keydown on the 8 key\n            if(event.code == ecodes.KEY_8 and event.value==1):\n                print(\"Detected keydown event on the 8\")\n\n            # Or use categorize. This is more useful if we want to write a function to\n            # return a text representation of the button press on a key down\n            #print(categorize(event))\n            data = categorize(event)\n            if(data.keycode==\"KEY_5\" and data.keystate==data.key_down):\n                print(\"Detected keydown event on the 5\")\n            else:\n                print(data.keycode, \"up\/down\")\n            print()\n\nwhile True:\n    readInputEvent(irin)\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Small infrared remotes are a cheap way to add a level of remote control to [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[34,35],"tags":[],"class_list":["post-396","post","type-post","status-publish","format-standard","hentry","category-gpio-hardware","category-raspberry-pi"],"_links":{"self":[{"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/posts\/396","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/comments?post=396"}],"version-history":[{"count":2,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/posts\/396\/revisions"}],"predecessor-version":[{"id":1277,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/posts\/396\/revisions\/1277"}],"wp:attachment":[{"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/media?parent=396"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/categories?post=396"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/tags?post=396"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}