ESP32 IR remote decoder
Decode an infrared remote's keys on an ESP32-C3 with the IRremote library, and toggle an LED with the power key.
Input · Intermediate
In a real product: Smart TV box (Consumer electronics): Decodes the remote's infrared keys to control the box.
The same IRremote library that decodes a TV remote on an Arduino runs on the ESP32. On an AVR it samples the receiver from a timer interrupt every 50 µs; on the ESP32 it does the same with one of the chip's hardware timers. Click a key on the remote while the simulation runs: the serial monitor shows its command, and the power key toggles the LED.
What you'll learn
- Using
IrReceiver.begin(),decode()andresume()on an ESP32 - Telling a new key press from the repeat frames a held key sends
- Powering a receiver module from the ESP32's 3.3 V
How it works
The receiver runs from 3V3, so its DAT output swings between 0 and 3.3 V, which an ESP32 pin takes directly. DAT goes to GPIO 4. It is LOW while the 38 kHz carrier is received, so each key press becomes an NEC frame: a 9 ms burst, a 4.5 ms space, then 32 bits whose spaces are short (0) or long (1).
IrReceiver.decode() returns true once a whole frame has arrived; decodedIRData.command is the key's code. A held key sends a short repeat frame every 108 ms, flagged with IRDATA_FLAGS_IS_REPEAT: the sketch ignores those, so holding the power key toggles the LED only once.
Try this
- Make the + and − keys dim the LED with
analogWrite. - Print the key's name instead of its code, with a
switchas in the Arduino IR example. - Count how many repeat frames a long press sends.
sketch.ino
// An IR receiver on GPIO 4: each key's command on the serial monitor; the power key toggles the LED on GPIO 2.
#include <IRremote.hpp>
const int IR_PIN = 4;
const int LED = 2;
const uint8_t POWER = 0xA2;
bool on = false;
void setup() {
Serial.begin(115200);
pinMode(LED, OUTPUT);
IrReceiver.begin(IR_PIN);
Serial.println("Press a key on the remote");
}
void loop() {
if (IrReceiver.decode()) {
if (!(IrReceiver.decodedIRData.flags & IRDATA_FLAGS_IS_REPEAT)) {
uint8_t command = IrReceiver.decodedIRData.command;
Serial.printf("Key 0x%02X\n", command);
if (command == POWER) {
on = !on;
digitalWrite(LED, on);
}
}
IrReceiver.resume(); // ready for the next frame
}
}