Infrared remote control: decode and send NEC codes

A TV remote sends commands as flashes of invisible infrared light (about 940 nm). The light does not stay on during a flash. It blinks at a carrier frequency of 38 kHz. A receiver module, for example the VS1838B or the TSOP38238, only responds to light that blinks at this frequency. It removes the carrier and gives a clean digital signal that is LOW during each burst. The ESP32 measures the length of the bursts and the spaces and decodes the command.

Many low-cost remotes use the NEC protocol: one frame contains an 8-bit address, an 8-bit command and their inverted copies. With an IR LED, the ESP32 can also send codes and control a TV, a fan or an LED strip. The same 38 kHz receivers also make long-range light barriers. Refer to IR break-beam sensors.

Small IR receiver module with a black receiver on a black board and three pins, next to a black 17-key remote with number keys, star, hash, arrow keys and OK
IR receiver module (HX1838) and the 17-key NEC remote from many starter kits.
Photo: Goga504, CC BY-SA 4.0

Receiver output: the last 1.2 seconds

Press a key. Hold it to send repeat codes.

Zoom into one transmission

—

Drag the trace to pan. Use the mouse wheel or the slider to zoom. The top trace is the IR LED: each burst is many 38 kHz pulses (zoom in to see them). The bottom trace is the receiver OUT pin: LOW during a burst, HIGH during a space.

FieldBits in time order (LSB first)ValueCheck
Press a key on the remote…

Learn table: codes received

Each new key adds a row, the same as a “learn” sketch on a real ESP32. Copy the command values into your switch statement.

KeyAddressCommanddecodedRawDataFramesRepeats
No codes yet.

How it works

38 kHz carrier

Sunlight and lamps also contain infrared light. But this light does not blink at 38 kHz. The receiver has a band-pass filter and automatic gain control, so it ignores the steady light and only responds to the carrier. One carrier period is 26.3 µs. The LED is usually on for about one third of each period.

The receiver module

The VS1838B, TSOP38238 and similar parts contain a photodiode, an amplifier, the filter and a demodulator. The output is active LOW: LOW while a burst arrives, HIGH (internal pull-up) at idle. Each burst must be longer than about 10 carrier cycles. The NEC bursts are 21 cycles or more.

NEC frame

A frame starts with a 9 ms burst and a 4.5 ms space. Then 32 bits follow: address, inverted address, command, inverted command. Each byte is sent LSB first. A final 562.5 µs burst ends the frame. A complete frame takes about 68 ms (67.5 ms plus the stop burst).

Bits: the space is the value

Each bit is a 562.5 µs burst and a space. A 0 has a 562.5 µs space (1.125 ms total). A 1 has a 1687.5 µs space (2.25 ms total). This is pulse-distance coding. The inverted copies make the number of 1 bits always 16, so every standard frame has the same length.

Repeat codes

When you hold a key, the remote does not send the full frame again. It sends a short repeat code: a 9 ms burst, a 2.25 ms space and a 562.5 µs burst. The repeat codes come every 108 ms (start to start). IRremote then sets the flag IRDATA_FLAGS_IS_REPEAT.

Extended NEC

Many remotes need more than 256 addresses. They use the second byte as the high byte of a 16-bit address, so the address byte and its “inverse” do not match. The command and its inverse always match. IRremote reports these remotes as NEC with an address above 0xFF.

NEC timing summary

PartBurst (LED on, 38 kHz)Space (LED off)Receiver OUT
Header (leader)9 ms4.5 msLOW 9 ms, HIGH 4.5 ms
Bit 0562.5 µs562.5 µsShort HIGH
Bit 1562.5 µs1687.5 µsLong HIGH
Stop burst562.5 µs—Ends the last space
Repeat code9 ms + 562.5 µs2.25 msEvery 108 ms while held

Wiring

ESP32 GPIO 27 GND 3V3 GPIO 25 5V / VIN VS1838B 1 OUT 2 GND 3 VCC 100 nF OUT: LOW = burst 3.3 V supply 1 kΩ NPN (PN2222 or 2N2222) IR LED 940 nm 47 Ω 5 V
Top: the receiver. Supply it from 3.3 V, so the OUT pin never goes above 3.3 V. Add 100 nF near the receiver. Bottom: the transmitter. A GPIO gives only about 10–20 mA. The transistor lets the IR LED get about 70 mA peak from 5 V, so the range is some meters. The pinout in the diagram is for a bare VS1838B or TSOP382xx. Modules have different pin orders.

VS1838B pinout

front view: dome toward you 1 2 3 OUT GND VCC to GPIO 27 LOW = burst to 3V3 2.7–5.5 V
PinNameConnect to
1OUTGPIO 27
2GNDGND
3VCC3V3

Hold the receiver with the dome toward you and the legs down: the pins are OUT, GND, VCC from left to right. The TSOP38238 has the same order. On a 3-pin module, do not use this order: read the labels on the board (S or OUT, + or VCC, − or GND). If you connect VCC and GND the wrong way, the receiver becomes hot and is damaged in a few seconds.

Connections

Part pinConnect toNotes
Receiver OUT (S)GPIO 27Active LOW. The receiver has its own pull-up.
Receiver GND (−)GND
Receiver VCC (+)3V3VS1838B: 2.7–5.5 V. TSOP38238: 2.5–5.5 V.
Transistor baseGPIO 25 through 1 kΩIRremote makes the 38 kHz carrier on this pin.
IR LED5 V → 47 Ω → LED → collectorLED cathode (short leg) to the collector.
Transistor emitterGND

Examine the pinout of your receiver. A bare VS1838B or TSOP382xx is OUT, GND, VCC (left to right, dome toward you). Many 3-pin modules (for example the HX1838 board) are labeled S, +, − in a different order. An incorrect connection can destroy the receiver. For a logic-level MOSFET as the switch, refer to MOSFETs.

Transistor: PN2222 or 2N2222. Both work the same in this circuit. The PN2222 is the plastic (TO-92) version of the 2N2222. But the pin order is not the same on all parts: the PN2222A is E-B-C (flat side toward you, legs down), and the P2N2222A and many plastic “2N2222” parts are C-B-E. Look at the datasheet of your part before you connect it. If the collector and emitter are swapped, the IR LED gets very little current and the range is short.

Low-power option: IR LED without a transistor

For a short range (about 1 m), the GPIO can drive the IR LED directly. You need only one resistor. This is good for a test on your desk, or to control a device that is near.

ESP32 GPIO 25 GND 100 Ω IR LED + −
GPIO 25 → 100 Ω → LED anode (long leg). LED cathode (short leg) → GND.
  • Current: (3.3 V − 1.3 V) ÷ 100 Ω ≈ 20 mA in each burst. This is a safe current for an ESP32 pin. Do not use less than 68 Ω.
  • Range: about 1 m, against about 5 m or more with the transistor driver at 70 mA.
  • Code: no change. Sketch 3 works with this circuit. Only the range is shorter.
  • When to use the transistor: for a TV across the room, for two IR LEDs, or for the TV-B-Gone.

Build steps

  1. Install the libraryIn the Library Manager, search for “IRremote” and install the library by Armin Joachimsmeyer (version 4.x).
  2. Connect the receiverRead the pin labels. Connect OUT to GPIO 27, VCC to 3V3 and GND to GND.
  3. Upload sketch 1Open the Serial Monitor at 115200 baud. Point the remote at the receiver and press each key. Each key prints its address and command.
  4. Write down the codesMake a table of the command values, the same as the learn table above.
  5. Add the transmitterBuild the transistor circuit. Look at the IR LED through a phone camera while sketch 3 runs. You see a weak flash.

Code

These sketches use the “IRremote” library 4.x. Versions 3 and older have a different API (IRrecv irrecv(pin), results.value). Old examples on the internet do not compile with version 4.

1 · Print the received NEC codes

ir_print_codes.ino


              #include <IRremote.hpp>

              const int IR_RECEIVE_PIN = 27;

              void setup() {
                Serial.begin(115200);
                // no feedback LED: LED_BUILTIN is GPIO 2, a strapping pin
                IrReceiver.begin(IR_RECEIVE_PIN, DISABLE_LED_FEEDBACK);
                Serial.println("Ready. Point the remote at the receiver and press keys.");
                Serial.println("protocol  address  command  raw data");
              }

              void loop() {
                if (!IrReceiver.decode()) return;        // nothing received yet

                IRData &d = IrReceiver.decodedIRData;
                bool repeat = d.flags & IRDATA_FLAGS_IS_REPEAT;

                if (d.protocol == NEC) {
                  if (repeat) {
                    // key held down: NEC sends a short repeat code, not the full frame
                    Serial.printf("NEC       0x%02X     0x%02X     (repeat: key held)\n",
                                  d.address, d.command);
                  } else {
                    Serial.printf("NEC       0x%02X     0x%02X     0x%08lX\n",
                                  d.address, d.command, (unsigned long)d.decodedRawData);
                  }
                } else if (d.protocol == UNKNOWN) {
                  Serial.println("Unknown signal: noise, or a frame that was not complete");
                } else {
                  Serial.print("Not NEC: ");
                  Serial.println(getProtocolString(d.protocol));
                }
                IrReceiver.resume();                     // get ready for the next frame
              }
            

Example output with the kit remote (key 1, then OK held down):


            NEC       0x00     0x45     0xBA45FF00
            NEC       0x00     0x1C     0xE31CFF00
            NEC       0x00     0x1C     (repeat: key held)
          

The raw data has the four bytes in the order of the frame, with the first byte at the right: address, inverted address, command, inverted command. So 0xBA45FF00 is 0x00, 0xFF, 0x45, 0xBA. Remotes with a 16-bit address (extended NEC) show 4 hex digits in the address column.

2 · Receive and act on keys

ir_receive.ino


              #include <IRremote.hpp>

              const int IR_RECEIVE_PIN = 27;
              const int LED_PIN = 4;
              bool ledOn = false;

              void setup() {
                Serial.begin(115200);
                pinMode(LED_PIN, OUTPUT);
                // no feedback LED: LED_BUILTIN is GPIO 2, a strapping pin
                IrReceiver.begin(IR_RECEIVE_PIN, DISABLE_LED_FEEDBACK);
              }

              void loop() {
                if (!IrReceiver.decode()) return;     // nothing received yet

                IrReceiver.printIRResultShort(&Serial); // protocol, address, command
                bool repeat = IrReceiver.decodedIRData.flags & IRDATA_FLAGS_IS_REPEAT;

                if (IrReceiver.decodedIRData.protocol == NEC && !repeat) {
                  switch (IrReceiver.decodedIRData.command) {
                    case 0x1C:                        // OK key on the kit remote
                      ledOn = !ledOn;
                      digitalWrite(LED_PIN, ledOn);
                      break;
                    case 0x45: Serial.println("Key 1"); break;
                    case 0x46: Serial.println("Key 2"); break;
                  }
                }
                IrReceiver.resume();                  // get ready for the next frame
              }
            

Ignore repeats for on/off keys. For volume or brightness keys, use the repeats: each repeat makes one more step.

3 · Send NEC codes

ir_send.ino


              // no LED_BUILTIN blink
              #define NO_LED_SEND_FEEDBACK_CODE   // before the include
              #include <IRremote.hpp>

              const int IR_SEND_GPIO = 25;      // to the transistor base through 1 kΩ

              void setup() {
                Serial.begin(115200);
                IrSender.begin(IR_SEND_GPIO);   // the 38 kHz carrier uses LEDC (PWM)
              }

              void loop() {
                // address 0x00, command 0x1C ("OK"), 0 repeat codes
                IrSender.sendNEC(0x00, 0x1C, 0);
                Serial.println("Sent OK");
                delay(2000);

                // hold "up" (0x18) for about 0.5 s: 1 frame + 4 repeat codes
                IrSender.sendNEC(0x00, 0x18, 4);
                delay(2000);
              }
            

Test the transmitter with a second ESP32 that runs sketch 1. You can also point the LED at the receiver on the same board. Each burst is 38 kHz PWM at about 30 % duty cycle.

Troubleshooting

Nothing is received

Examine the pinout again. Make sure that the remote has a good battery (look at it through a phone camera). Make sure that the receiver is for 38 kHz. Use the pin number from your wiring in IrReceiver.begin().

Protocol is UNKNOWN

The remote uses a protocol other than NEC (for example Sony, RC5 or an air-conditioner protocol). IRremote decodes many protocols. Print the result with printIRResultShort() to see the name. Fluorescent lamps and LED drivers can also cause noise.

Old code does not compile

You use an example for IRremote 2.x or 3.x. Use #include <IRremote.hpp>, IrReceiver.begin() and IrReceiver.decodedIRData. Use the examples in the IDE under File → Examples → IRremote.

Short range when sending

A GPIO alone gives only about 20 mA, so the range is about 1 m. For more range, use the transistor driver. Point the LED at the receiver. A wide-angle LED gives less range than a narrow LED.

Each press gives many codes

You did not test the repeat flag. Ignore frames with IRDATA_FLAGS_IS_REPEAT for on/off actions.

Alternative: IRremoteESP8266

The “IRremoteESP8266” library (also for the ESP32) is good for air-conditioner remotes with long frames. Version 2.9.0 or later supports the Arduino-ESP32 core 3.x. Its API is different from IRremote.

Resources