Home

Guide no. 93

A 38 kHz receiver and the IRremote library: read the codes of any remote, even the TV one, and use the keys to turn on an LED, change the color of an RGB LED and move a servo.

By Ada Intelisano · informaticait.it technical team

Download the PDF (A4, 11 pages) Free to print and share, without changes — CC BY-ND 4.0
In short
  • The receiver has three pins: S to pin 2, + to 5 V, − to GND.
  • The IRremote library turns every key into protocol, address and command.
  • The first sketch reads the commands of any remote: you copy them into the others.
  • On the UNO, IRremote takes the PWM of pins 3 and 11, the Servo library that of pins 9 and 10.
Time: 50 minutesLevel: beginnerBefore: guides no. 34, 41 and 46

Every remote control talks with a light our eyes can't see. In this guide Arduino learns to listen to it. You'll read the key codes of any remote, even the TV one, and use them to turn on an LED, change the color of an RGB LED and turn the arm of a servo.

1Get the parts ready

What is in the kit123456789*0#▲◀▶▼OKS−S−+38 kHz receiverS signal · + 5 V · − groundremote control, 17 keysthree-wire jumperinformaticait.it
  • the remote control kit with receiver for 38 kHz: remote, receiver on a small board and a three-wire jumper
  • Arduino UNO (a compatible board is fine) with its USB cable
  • a 400-point breadboard, male-to-female and male-to-male jumper wires
  • from step 8: the KY-009 RGB LED module, three 330 Ω resistors and an SG90 micro servo
New word: infraredLight of a color the human eye can't see. The LED in the remote switches it on and off very quickly, in bursts: each key has its own sequence.

2How the signal travels

From key press to numberArduinoremotereceiverS pin1 Light from the remote: bursts of flashesinside each burst 38,000 flashes per second (38 kHz)2 Receiver S pin: low during each burst5 V0 V3 The IRremote library measures the timingand finds protocol, address and commandnot to scaleinformaticait.it

Inside the receiver there is a light sensor, an amplifier and a filter tuned to 38 kHz: it keeps the light that flashes 38,000 times a second and rejects the steady light of the sun or of light bulbs. What reaches the S pin is already a clean series of bursts: at rest the pin is high, and during each burst it drops to 0 V. The IRremote library does the rest: it measures how long the bursts and pauses last and gets three pieces of information out of them.

New word: protocol, address, commandThe protocol is the rule a remote uses to turn a key into flashes: the most common ones have a name, such as NEC, Sony, RC5 or Samsung. The address is often the same for all the keys of a remote. The command changes from one key to another: it's the number we'll use.

3Install the IRremote library

In the Arduino IDE open the Library Manager, search for IRremote and install the one by shirriff, z3t0, ArminJo. Our sketches are tested with version 4.7.1.

Watch out for old examples you find online: if they contain irrecv.decode(&results) they were written for version 2 of the library and don't work with the current one.

4Connect the receiver

The breadboard shares out the 5 V and ground: soon three parts will use them. Follow the drawing below.

  • 5V on the UNO → top + rail of the breadboard (red wire), GND → top − rail (black wire). Both wires run around the left side of the board.
  • The receiver stays off the breadboard, connected with three male-to-female jumper wires: − to the − rail, the middle pin (+) to the + rail, S to column 21, row j.
  • A short yellow jumper from f to e in column 21 takes the signal to the lower half. From row a of the same column a jumper wire goes to pin 2.

The small board has S and − printed on it; the middle pin, with no marking, is the +. Check the markings on your module before wiring it: the pin order changes from one manufacturer to another.

The receiver on the breadboardjjiihhggffeeddccbbaa115510101515202025253030−+−+SCLSDAAREFGND131211109876543210IOREFRESET3.3V5VGNDGNDVINDIGITAL (PWM ~)POWERANALOG INUNOS−25VGNDIR receiverfrom the kit−+S5V → top + railGND → top − railreceiver S → pin 2informaticait.it
✓ Done?Three wires from the receiver: S goes to pin 2, + to the + rail, − to the − rail. The + rail gets 5V, the − rail GND.

5Read the key codes

// Press a key on the remote: Arduino writes its code in the Serial Monitor.
#include <Arduino.h>
#include <IRremote.hpp>      // the IRremote library

const int IR_PIN = 2;        // the S pin of the receiver

void setup() {
  Serial.begin(115200);
  IrReceiver.begin(IR_PIN, ENABLE_LED_FEEDBACK);   // the L LED blinks at every signal
  Serial.println("Ready: press a key on the remote");
}

void loop() {
  if (IrReceiver.decode()) {                       // has a signal arrived?
    IRData &data = IrReceiver.decodedIRData;       // what the library understood
    if (data.flags & IRDATA_FLAGS_IS_REPEAT) {
      Serial.println("  ...key held down");
    } else if (data.protocol == UNKNOWN) {
      Serial.println("Signal not recognized: try again");
    } else {
      Serial.print("Protocol: ");
      Serial.print(getProtocolString(data.protocol));
      Serial.print("   address: 0x");
      Serial.print(data.address, HEX);
      Serial.print("   command: 0x");
      Serial.println(data.command, HEX);
    }
    IrReceiver.resume();                           // ready for the next key
  }
}

Upload the sketch, open the Serial Monitor at 115200 and point the remote at the receiver. Press one key at a time, without rushing.

✓ What you should seeEach key prints a line with the name of the protocol and two numbers: address: 0x... and command: 0x... (the numbers depend on your remote). The board's L LED blinks when the light arrives. If you hold a key down you get ...key held down.
New word: hexadecimal0x10 is a number written in base 16: the 0x in front tells you so. No math needed: copy it as it is, with the 0x, into the table below.

Write your codes here (you'll need them in steps 7, 9 and 10):

KeyCommand on your remoteAdafruit 389 mini remote
10x10
20x11
30x12
00x0C
left arrow0x08
right arrow0x0A
OK (called Enter on the 389)0x09

Adafruit 389 column: commands we worked out from the codes Adafruit publishes for this remote. They are the numbers already written in the sketches.

If it doesn't work
  • No lines at all: check the S wire on pin 2, + and − on the right rails, and the 115200 speed at the bottom of the Serial Monitor.
  • Is the remote new? See whether a plastic tab is insulating the battery: pull it out (the Adafruit mini remote has one).
  • “Signal not recognized” on every key: move closer, the signal may be arriving weak; if nothing changes, that remote uses a protocol the library doesn't know.

6Try the TV remote

Grab the remotes around the house: TV, set-top box, stereo. The library recognizes the most common protocols (NEC, Sony, RC5, RC6, Samsung, LG, Panasonic, JVC, Denon and others) and prints the name of each one. With the ones it doesn't know you get “Signal not recognized”. Air conditioners are a special case: they send much longer messages and the library may not recognize them, or it may print PulseDistance, meaning it understands the shape of the signal but can't split it into address and command. A remote that flashes at a frequency other than 38 kHz is also picked up less well: the receiver's filter is tuned to that frequency.

Remember that the light reaches everything in the room: if you use the TV's volume keys to control Arduino, the TV will change its volume too.

7One key turns on the LED

// A key on the remote turns the board's L LED on and off (pin 13).
#include <Arduino.h>
#include <IRremote.hpp>

const int IR_PIN = 2;              // the S pin of the receiver
const int LED_PIN = 13;            // the L LED, already on the board
const uint16_t KEY_LED = 0x10;     // key 1 of the Adafruit 389 remote: write yours

bool ledOn = false;                // at the start the LED is off

void setup() {
  pinMode(LED_PIN, OUTPUT);
  IrReceiver.begin(IR_PIN, DISABLE_LED_FEEDBACK);  // now we control the L LED ourselves
}

void loop() {
  if (IrReceiver.decode()) {
    bool held = IrReceiver.decodedIRData.flags & IRDATA_FLAGS_IS_REPEAT;
    if (!held && IrReceiver.decodedIRData.command == KEY_LED) {
      ledOn = !ledOn;                                // off becomes on and vice versa
      digitalWrite(LED_PIN, ledOn ? HIGH : LOW);
    }
    IrReceiver.resume();
  }
}

Pick a key and write its command in place of 0x10 in the KEY_LED line. With the Adafruit 389 mini remote leave 0x10: it's its key 1. The LED is the L LED already on the board, on pin 13: there's nothing to connect. That's why DISABLE_LED_FEEDBACK tells the library to stop using it for blinking.

New word: the oppositeIn ledOn = !ledOn the exclamation mark means “the opposite”: if ledOn was true it becomes false, and vice versa. That way the same key turns the LED on and off.
✓ What you should seePress the key: the L LED turns on. Press it again: it turns off. The other keys do nothing. If you hold the key down, the LED doesn't flicker: the repeats are thrown away.
If it doesn't work
  • Nothing happens: is the command written in the sketch really the one for that key? Check it against the table, letter by letter.
  • The LED keeps turning on and off while you hold the key down: the !held check is missing from the if line.

8Add the RGB LED and the servo

The receiver stays where it is. The KY-009 module has four pins: B, G, R and − (common cathode). The markings are on the back; on our module, with the LED facing you and the pins at the bottom, the order from the left is B, G, R, −. There are no resistors on the small board: each color needs its own 330 Ω resistor (orange, orange, black, black, brown). Follow the drawing below.

  • B, G and R with three male-to-female jumper wires to columns 8, 9 and 10, row j; − to the top − rail.
  • The three resistors straddle the center channel, from f to e, in the same columns.
  • From row a of columns 8, 9 and 10, three jumper wires go to pins 7 (blue), 6 (green) and 5 (red).
  • The servo connector has three holes: push in three male-to-male jumper wires. Brown to the top − rail, red to the + rail, orange to column 5, row j. A short jumper from f to e in column 5 and a jumper wire from row a to pin 9.
New word: why 330 ΩOur product page for the KY-009 gives a maximum of 10 mA per color, with voltages from 1.8 to 3.5 V. In the worst case, at 1.8 V, (5 − 1.8) / 330 ≈ 9.7 mA flows: this is our own calculation, and it stays below the LED's 10 mA and below the 20 mA that Arduino gives for each pin.
Receiver, RGB LED and servojjiihhggffeeddccbbaa115510101515202025253030−+−+SCLSDAAREFGND131211109876543210IOREFRESET3.3V5VGNDGNDVINDIGITAL (PWM ~)POWERANALOG INUNOS−KY-009276595VGNDIR receiverfrom the kit−+SKY-009 RGB LEDpins: B G R −330 ΩSG90 servo5V → top + railGND → top − railreceiver S → pin 2R → 330 Ω → pin 5G → 330 Ω → pin 6B → 330 Ω → pin 7servo signal → pin 9informaticait.it

9Change color with the keys

// Keys 1, 2 and 3 turn red, green and blue on and off; key 0 turns everything off.
#include <Arduino.h>
#include <IRremote.hpp>

const int IR_PIN = 2;              // the S pin of the receiver
const int RED_PIN = 5;             // R of the RGB LED module (goes through its resistor)
const int GREEN_PIN = 6;           // G
const int BLUE_PIN = 7;            // B

// the commands of keys 1, 2, 3 and 0 on the Adafruit 389 mini remote:
// with another remote write the ones you read with the first sketch
const uint16_t KEY_1 = 0x10;
const uint16_t KEY_2 = 0x11;
const uint16_t KEY_3 = 0x12;
const uint16_t KEY_0 = 0x0C;

bool red = false;
bool green = false;
bool blue = false;

void show() {                      // turns on the colors that are true
  digitalWrite(RED_PIN, red ? HIGH : LOW);
  digitalWrite(GREEN_PIN, green ? HIGH : LOW);
  digitalWrite(BLUE_PIN, blue ? HIGH : LOW);
}

void setup() {
  pinMode(RED_PIN, OUTPUT);
  pinMode(GREEN_PIN, OUTPUT);
  pinMode(BLUE_PIN, OUTPUT);
  IrReceiver.begin(IR_PIN, ENABLE_LED_FEEDBACK);
}

void loop() {
  if (IrReceiver.decode()) {
    bool held = IrReceiver.decodedIRData.flags & IRDATA_FLAGS_IS_REPEAT;
    uint16_t key = IrReceiver.decodedIRData.command;
    if (!held) {                   // a color changes only on the first press
      if (key == KEY_1) red = !red;
      if (key == KEY_2) green = !green;
      if (key == KEY_3) blue = !blue;
      if (key == KEY_0) {
        red = false;
        green = false;
        blue = false;
      }
      show();
    }
    IrReceiver.resume();
  }
}

Write the commands of your keys 1, 2, 3 and 0 in the four KEY_ lines. Each key turns one color on or off; two colors together mix as in guide no. 46: 1 and 2 make yellow, all three make white. 0 turns everything off.

New word: timerA counter inside the microcontroller: among other things it handles the PWM of two pins. The IRremote library uses the one for pins 3 and 11, the Servo library the one for pins 9 and 10. That's why here the colors are only switched on or off with digitalWrite: seven colors plus black. If you want shades with analogWrite, pins 5 and 6 are still free. For the same reason, no tone() for a buzzer: it uses the same timer as IRremote and, as the library documentation says, reception stops after a tone().
✓ What you should seePress 1: red. Press 2: red and green together, which makes yellow. Press 1 again: only green is left. 0 turns everything off.
If it doesn't work
  • One color never lights up: check its jumper wire and its resistor, which must go exactly from f to e in the same column.
  • The colors come out swapped: your module has its pins in a different order. Follow the markings on the back, not the drawing.

10Move the servo with the arrows

// The arrows turn the servo 10 degrees at a time, OK brings it back to the center.
#include <Arduino.h>
#include <IRremote.hpp>
#include <Servo.h>

const int IR_PIN = 2;              // the S pin of the receiver
const int SERVO_PIN = 9;           // the orange wire of the servo

// the commands of the arrows and of Enter on the Adafruit 389 mini remote:
// with another remote write the ones you read with the first sketch
const uint16_t KEY_LEFT = 0x08;
const uint16_t KEY_RIGHT = 0x0A;
const uint16_t KEY_OK = 0x09;

Servo arm;
int angle = 90;                    // we start from the center

void setup() {
  arm.attach(SERVO_PIN);
  arm.write(angle);
  IrReceiver.begin(IR_PIN, ENABLE_LED_FEEDBACK);
}

void loop() {
  if (IrReceiver.decode()) {
    uint16_t key = IrReceiver.decodedIRData.command;     // also while a key is held down
    if (key == KEY_LEFT) angle = angle + 10;
    if (key == KEY_RIGHT) angle = angle - 10;
    if (key == KEY_OK) angle = 90;
    angle = constrain(angle, 0, 180);                    // never below 0 or above 180
    arm.write(angle);
    IrReceiver.resume();
  }
}

Write the commands of your arrows and of the OK key in the three KEY_ lines.

Here the repeats come in handy: as long as you hold an arrow down the remote keeps sending the signal and the arm moves 10 degrees at a time. constrain keeps the angle between 0 and 180; OK brings it back to 90.

✓ What you should seeA short press moves the arm 10 degrees; if you hold the key down it keeps going all the way. OK puts it back in the center.
If it doesn't work
  • The arm turns the wrong way: swap + 10 and - 10 in the lines of the two arrows.
  • The servo moves in jerks or the board restarts: Adafruit says this can be a power problem and that some USB ports don't supply enough current for the board and the servo together. Try another port or a power supply.
  • The receiver gets things wrong only while the servo is moving: the motor can disturb the 5 V. For a noisy power supply, Vishay, the maker of the receiver, recommends a resistor in series on the receiver's + and a capacitor between its + and its −.

11Other receivers

The bare receiver1 OUT2 GND3 VCClens facing you1 OUT: output → pin 22 GND: ground → −3 VCC: 5 V → +same order for the TSOP38238informaticait.it

You can also get the receiver without a board, for example our 1838 in packs of three or the Vishay TSOP38238. It goes straight into the breadboard: with the lens facing you the legs are, from the left, OUT, GND and VCC. OUT goes to pin 2, GND to the − rail, VCC to the + rail. According to the TSOP382 datasheet the output pull-up resistor is already inside the receiver: you don't need to add one.

The Seeed Studio Grove receiver uses the same Vishay part and a four-wire cable: yellow is the signal, red VCC, black GND, white not connected.

12Challenge yourself

Try it yourself
  • Combine the two sketches: arrows for the servo, 1, 2 and 3 for the colors. The setup() lines go together, the key checks inside the same if.
  • Make a parking barrier: OK raises the arm to 90 degrees, waits 3 seconds and goes back to 0.
  • Check the address too, with && IrReceiver.decodedIRData.address == ...: that way another remote with the same commands won't interfere.
✓ What you learned
  • the receiver filters the light at 38 kHz and gives clean pulses on the S pin;
  • IRremote turns every key into protocol, address and command: the command is the number to use;
  • with the first sketch you read the commands of any remote, then you write them into the others;
  • the repeats of a key held down can be thrown away or put to use.
Sources: Vishay, TSOP382.. TSOP384.., datasheet doc. 82491 rev. 2.1 · IRremote library 4.7.1 (Arduino-IRremote): README and examples · Adafruit, products 157 and 389, mini remote codes and the guide “Using an Infrared Library on Arduino” · Seeed Studio, Grove - Infrared Receiver wiki and Grove standard · Arduino, UNO R3 Tech Specs, Servo library 1.3.0, tone() and analogWrite() reference · informaticait product pages 2867, 1909, 5031 and 2024 · informaticait guides no. 34, 41 and 46

Useful products

Other guides

All our guides →
Loading...
Back to top