IR remote decoder
Decode the keys of an infrared remote control with an IR receiver and the IRremote library.
Input · Intermediate
In a real product: Air conditioner (Smart home): The indoor unit decodes the remote's commands.
TV remotes send their keys as flashes of infrared light, switched on and off 38 000 times a second in a pattern. An IR receiver module turns that into a clean digital signal, and the IRremote library decodes it into a key code.
What you'll learn
- How IR remote protocols (here NEC) encode a key
- Using the IRremote library:
IrReceiver.begin(),decode()andresume() - Mapping codes to names with a
switch
How it works
The receiver's DAT pin goes to pin 2. It is LOW while it sees the 38 kHz carrier and HIGH otherwise, so a key press becomes a train of pulses.
An NEC frame is a 9 ms burst, a 4.5 ms gap, then 32 bits: the address, the command, and both again inverted as a check. The length of each gap says whether a bit is 0 or 1. IrReceiver.decode() measures them and fills in decodedIRData.command. Holding a key sends short repeat codes, which this sketch skips.
Try this
- Click the remote's keys while the simulation runs.
- Make the number keys set an LED's brightness, and POWER switch it off.
- Control a servo or a stepper with the arrow keys.
sketch.ino
// Decode an IR remote on pin 2 with the IRremote library and print each key.
#include <IRremote.hpp>
const int IR_PIN = 2;
const char *keyName(uint8_t command) {
switch (command) {
case 0xA2: return "POWER"; case 0xE2: return "MENU"; case 0x22: return "TEST";
case 0x02: return "PLUS"; case 0xC2: return "BACK"; case 0xE0: return "PREV";
case 0xA8: return "PLAY"; case 0x90: return "NEXT"; case 0x98: return "MINUS";
case 0xB0: return "C"; case 0x68: return "0"; case 0x30: return "1";
case 0x18: return "2"; case 0x7A: return "3"; case 0x10: return "4";
case 0x38: return "5"; case 0x5A: return "6"; case 0x42: return "7";
case 0x4A: return "8"; case 0x52: return "9";
default: return "?";
}
}
void setup() {
Serial.begin(9600);
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.print("Key 0x");
Serial.print(command, HEX);
Serial.print(": ");
Serial.println(keyName(command));
}
IrReceiver.resume(); // ready for the next frame
}
}