Control your Raspberry Pi with an IR remote

Use the little IR remote from the kit to control your Raspberry Pi. The Linux kernel decodes the remote for you; Python reads each button with evdev and switches LEDs, dims one, and clicks a relay that turns a lamp...
  • Level:Advanced
  • Duration: 1 h 15 min
  • Ages 12+
  • Platform: Raspberry Pi

What you'll need

Control your Raspberry Pi with an IR remote – EEMENTOR STEM™ lesson

Every TV remote talks in flashes of invisible infrared light. In this project the Raspberry Pi learns to understand the small remote from your kit, and you use it to switch LEDs, dim one, and click a relay that turns a lamp on and off from across the room. The best part: you don't decode the flashes yourself. The Linux kernel on the Pi has an IR driver built in. You switch it on with one line in a settings file, and every button press arrives in Python as an input event, just like a key on a keyboard. If you built the smart relay panel, this gives it a remote control.

What you'll learn

  • How an IR remote sends its buttons as pulses of infrared light
  • How to switch on the kernel's IR driver with a device tree overlay
  • How to find the code of every button with ir-keytable
  • How to read input events in Python with the evdev library
  • How to deal with buttons that repeat while you hold them

What you need

  • Raspberry Pi 4 Model B with Raspberry Pi OS (see the first starter lesson) and its USB-C power supply, connected to the internet for the installs
  • IR remote control and IR receiver module (ESP32 IoT Starter Kit)
  • 2-channel relay module (ESP32 IoT Starter Kit)
  • A red, a yellow, a green and a white LED, and four 220 Ω resistors (ESP32 IoT Starter Kit)
  • Breadboard and male-to-male wires (ESP32 IoT Starter Kit)
  • Female-to-male jumper wires from the Pi to the breadboard, or a female-female and a male-male Dupont wire from the kit plugged together

Safety first: in this lesson the relay only switches the white LED on the 5V rail. A relay module can look as if it is made for mains, but never connect anything that plugs into a wall socket: mains voltage can kill. Power the IR receiver from 3V3, not 5V, so its signal is safe for the Pi's 3.3 V GPIO pins. Shut the Pi down and unplug it before you change the wiring.

Wiring

Breadboard wiring diagram: IR receiver module with S on GPIO 23 and + on 3V3; red, yellow and green LEDs with 220 ohm resistors on GPIO 17, 27 and 22; 2-channel relay module with IN1 on GPIO 24, VCC on 5V, COM to 5V and NO through a 220 ohm resistor to a white LED; rails from 5V pin 2 and GND pin 9 of a Raspberry Pi 4.
Breadboard view. Check each connection against the wiring table below.
From To
IR receiver S (signal) GPIO 23 (pin 16)
IR receiver + / − 3V3 (pin 1) / GND rail
GPIO 17 (pin 11) 220 Ω → red LED long leg; short leg → GND rail
GPIO 27 (pin 13) 220 Ω → yellow LED long leg; short leg → GND rail
GPIO 22 (pin 15) 220 Ω → green LED long leg; short leg → GND rail
Relay VCC / GND / IN1 5V rail / GND rail / GPIO 24 (pin 18)
Relay COM (channel 1) 5V rail
Relay NO (channel 1) 220 Ω → white LED long leg; short leg → GND rail
Rails 5V (pin 2) to the + rail, GND (pin 9) to the − rail

The relay's screw terminals are on the opposite side to its pins: loosen a screw, push a stripped wire in and tighten it. NO means "normally open": it only connects to COM while the relay is on.

Step 1: Switch on the IR driver

  1. Open a terminal and edit the Pi's settings file: sudo nano /boot/firmware/config.txt
  2. At the very end, add this line, then save with Ctrl+O, Enter and quit with Ctrl+X:
    dtoverlay=gpio-ir,gpio_pin=23
  3. Install the two tools you need: sudo apt install ir-keytable python3-evdev
  4. Restart the Pi: sudo reboot

The overlay tells the kernel to load its IR receiver driver, called gpio_ir_recv, on GPIO 23. After the reboot, sudo ir-keytable lists it as a remote control device, usually rc0, with the protocols it understands.

Step 2: Find your remote's codes

Each button sends a number called a scancode. To see them, run this, point the remote at the receiver and press a few buttons. Stop it with Ctrl+C.

sudo ir-keytable -c -p all -t

-p all switches on every decoder, -t is test mode. Each press prints a line such as lirc protocol(nec): scancode = 0x45 and an EV_MSC event with the same scancode. The kit remote uses the NEC protocol, the most common one for small remotes. Write down the codes of the buttons you want to use.

The decoders reset when the Pi restarts. To switch the NEC decoder on at every boot, run sudo crontab -e, choose an editor if asked, and add this line at the end:

@reboot /usr/bin/ir-keytable -c -p nec -s rc0

Step 3: The program

Open Thonny, paste the program, save it as ir_control.py and click Run. If your remote's codes differ from the ones in BUTTONS, set LEARN = True, run it, press each button, and copy the codes it prints into the dictionary.

# Control the Raspberry Pi with an IR remote (Linux gpio-ir + evdev + gpiozero)
from gpiozero import LED, PWMLED, OutputDevice
from evdev import InputDevice, list_devices, ecodes
from time import monotonic

LEARN = False      # True: only print the scancode of each button you press

red = LED(17)
yellow = LED(27)
green = PWMLED(22)                                  # dimmable with up and down
lamp = OutputDevice(24, active_high=False, initial_value=False)   # relay: on when IN is LOW

# Scancodes of the kit remote (NEC). Yours may differ: run with LEARN = True to see them.
BUTTONS = {
    0x45: "1", 0x46: "2", 0x47: "3", 0x44: "4", 0x40: "5", 0x43: "6",
    0x07: "7", 0x15: "8", 0x09: "9", 0x16: "*", 0x19: "0", 0x0D: "#",
    0x18: "up", 0x52: "down", 0x08: "left", 0x5A: "right", 0x1C: "ok",
}
REPEATS = ("up", "down")   # these keep working while you hold the button


def find_receiver():
    for path in list_devices():
        device = InputDevice(path)
        if "gpio_ir_recv" in device.name:          # the name the gpio-ir driver uses
            return device
    raise SystemExit("No IR receiver found. Check the dtoverlay line in config.txt and reboot.")


def status():
    onoff = lambda x: "on " if x else "off"
    return (f"red {onoff(red.is_lit)}  yellow {onoff(yellow.is_lit)}  "
            f"green {int(green.value * 100):3d}%  lamp {onoff(lamp.value)}")


def press(name):
    if name == "1":
        red.toggle()
    elif name == "2":
        yellow.toggle()
    elif name == "3":
        green.value = 0 if green.value else 1
    elif name == "up":
        green.value = min(1, round(green.value + 0.1, 1))
    elif name == "down":
        green.value = max(0, round(green.value - 0.1, 1))
    elif name == "ok":
        lamp.toggle()                              # click: the relay switches the lamp
    elif name == "*":
        red.blink(on_time=0.2, off_time=0.2)       # party mode
        yellow.blink(on_time=0.2, off_time=0.2)
    elif name == "0":                              # everything off
        red.off()
        yellow.off()
        green.off()
        lamp.off()
    else:
        print(f"{name:>5}  (no job yet)")
        return
    print(f"{name:>5}  {status()}")


def main():
    remote = find_receiver()
    print(f"Listening to {remote.name} on {remote.path}. Press Ctrl+C to stop.")
    last_code, last_time = None, 0.0
    for event in remote.read_loop():
        if event.type != ecodes.EV_MSC or event.code != ecodes.MSC_SCAN:
            continue                               # only the scancode events interest us
        code, now = event.value, monotonic()
        name = BUTTONS.get(code)
        repeat = code == last_code and now - last_time < 0.35
        last_code, last_time = code, now
        if LEARN or name is None:
            if not repeat:
                print(f"Button with scancode 0x{code:02X}")
            continue
        if repeat and name not in REPEATS:
            continue                               # holding a button sends its code again and again
        press(name)


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("Bye!")

The buttons: 1, 2 and 3 switch the red, yellow and green LEDs; hold up or down to dim the green one; OK clicks the relay and the white "lamp" LED; * starts party mode and 0 switches everything off.

What you should see

The Shell says which device it is listening to. Every button you press prints its name and the state of all outputs, for example ok red on yellow off green 60% lamp on, and you hear the relay click. A button that isn't in the dictionary prints its scancode instead, so you can add it.

What you should see: ir-keytable test output with NEC scancodes 0x45 and 0x1c, then the Thonny Shell printing each button with the state of the red, yellow and green LEDs and the relay lamp, and an unknown button shown by its scancode.
First find the scancodes, then watch the program switch the outputs.

How it works

How it works: the remote flashes at 38 kHz, the receiver pulls GPIO 23 low, the gpio_ir_recv driver and NEC decoder produce a scancode, the kernel sends an EV_MSC MSC_SCAN input event, and Python looks it up in a dictionary; plus an NEC frame with its start burst and 32 bits.
The kernel decodes the light pulses; Python only sees one number per button.

The remote. The remote's LED flashes at 38,000 times a second, in bursts. The NEC protocol sends a long start burst, then 32 bits: an address, the command, and both again inverted as a check. The length of the pause after each short burst says whether a bit is a 0 or a 1. While you hold a button, the remote sends a short "repeat" signal about every 110 milliseconds.

The receiver. The receiver module only reacts to light flashing at 38 kHz, which filters out sunlight and lamps. Its output pin goes low during each burst, so the Pi sees a clean pattern of pulses on GPIO 23.

The kernel. The gpio_ir_recv driver times every pulse, and the NEC decoder turns the pattern into a scancode. The kernel then reports it as an input event of type EV_MSC with code MSC_SCAN, on a device in /dev/input, the same system that handles keyboards and mice.

Python. find_receiver() looks through the input devices for the one named gpio_ir_recv. read_loop() waits for events and hands them over one by one; the program keeps only the scancode events and looks the code up in BUTTONS. Because a held button keeps sending its code, a code that arrives again within 0.35 seconds counts as a repeat: up and down use the repeats to dim smoothly, every other button ignores them. The relay module switches on when its IN pin is low, which is why OutputDevice gets active_high=False.

Try this next

  • Use buttons 4 to 9 to start the timers or scenes from your smart relay panel.
  • Arm and disarm the keypad alarm with the remote, as well as with the PIN.
  • Find an old TV remote and teach the program its buttons with LEARN = True. It may use another protocol, such as RC-5 or Sony: -p all shows which.
  • Start the program at boot with a systemd service, so the remote works without a screen.

Troubleshooting

  • "No IR receiver found": check the dtoverlay line for typos, that it is in /boot/firmware/config.txt, and that you rebooted. sudo ir-keytable should list a device.
  • ir-keytable -t shows nothing: check the receiver's wiring, and that you used -p all. Point the remote straight at the receiver from about a metre. A phone camera can show whether the remote's LED flashes when you press a button.
  • Permission denied on /dev/input: your user must be in the input group. Run sudo usermod -aG input $USER and log out and in again.
  • It worked until a restart: the NEC decoder isn't switched on at boot. Check the @reboot line in sudo crontab -l.
  • The relay clicks but the white LED stays off: check that its wire goes to NO, not NC, and that COM gets 5V.
  • The relay is on when it should be off: your module switches on with a high signal. Change active_high=False to True.

Next lesson

Show motion in 3D in the browser with an MPU-6050: read a motion sensor over I2C and stream its tilt to a web page live.