Blog

How my Arduino IR station records a remote to SD and plays it back (and how I debugged it)

Infrared is invisible. That is handy for a remote, and annoying when your DIY playback does nothing. This is how my IR station records a remote control to an SD card, plays the code back through an IR LED, and how I debugged it on the bench with a logic analyzer and a scope.

It is one of the Arduino stations in my SmartHomeDIY system. The whole idea is that it learns the codes from any IR remote, so it can control a TV, an air conditioner, or anything else with an IR remote. The hub sends it a command over nRF24, and it plays the right code back. The sketch is open source: IR_STATION_WITH_SD on GitHub.

Video thumbnail: IR to SD to replay, 38 kHz carrier made in software

Full walkthrough (4:32). Loads from YouTube only after you press play. Open on YouTube. The narration in my videos is an AI voice; the sketch, captures and numbers are from my bench.

The IR station

The station is an Arduino with four things on it: an IR receiver on pin D2 for recording, an IR LED on pin 7 for playback, a micro SD card to keep the codes, and an nRF24L01 radio to take commands from the hub. The board can be an Uno or a Nano — both work, and the sketch is the same ATmega328 code.

Fritzing breadboard view of the IR station: Arduino Uno, nRF24L01, micro SD module, an infrared receiver module, an infrared LED module and four transistors
The breadboard view from my Fritzing file. Receiver and emitter are the two blue modules in the middle, the SD module and the nRF24L01 are on the left.

The SD card and the radio share one SPI bus, and that does not always work well. I solved it with four transistors that cut off whichever device is not in use, which is what the two yellow notes in the drawing say. I wrote that up in How to use multiple SPI devices with Arduino. In the sketch it comes down to two small functions that flip the switch lines and the chip selects:

void enableSD(void)
{
  digitalWrite(SD_SWITCH_LINE1, HIGH);
  digitalWrite(RF_SWITCH_LINE1, LOW);
  digitalWrite(Radio_CSN, HIGH); //Disable radio
  digitalWrite(SelectSD, LOW); //Enable sd-card
  delay(1000);
}

void enableRF(void)
{
  digitalWrite(SD_SWITCH_LINE1, LOW);
  digitalWrite(RF_SWITCH_LINE1, HIGH);
  digitalWrite(SelectSD, HIGH); //Disable sd-card
  digitalWrite(Radio_CSN, LOW); //Enable radio
  delay(10);
}

IR_STATION_WITH_SD.ino, lines 258–274

Recording: counting in 18 µs steps

The receiver output goes to pin D2 and the sketch reads the port register directly. The comment in the sketch says why: digitalRead() is too slow for this.

The loop counts how long the pin stays high, then how long it stays low. Each count is one step of 18 µs (RESOLUTION). One high count plus one low count is one pair, a space and a mark. A gap longer than MAXPULSE (3800 steps, about 68 ms) means the code is over.

#define IRpin_PIN      PIND
#define IRpin          2
// ...
#define MAXPULSE 3800
// ...
unsigned long RESOLUTION = 18;//20;
// ...
uint8_t pulses[120][2];  // pair is high and low pulse - need to optimize

IR_STATION_WITH_SD.ino, lines 128–143 (excerpt, // ... marks skipped lines)

void recordircode()
{
  highpulse = lowpulse = 0; // start out with no pulse length

  //  while (digitalRead(IRpin)) { // this is too slow!
  while (IRpin_PIN & (1 << IRpin)) {
    // ...
    highpulse++;
    delayMicroseconds(RESOLUTION);
    // ...
    if ((highpulse >= MAXPULSE) && (currentpulse != 0)) {
      Serial.println("break highpulse....");//dbg
      Serial.println(highpulse);//dbg
      printpulses();
      currentpulse = 0;
      return;
    }
  }
  // ...
  pulses[currentpulse][0] = highpulse;

IR_STATION_WITH_SD.ino, lines 467–496 (excerpt, // ... marks skipped lines)

Saving the code to the SD card

When the code ends, the sketch writes it to the SD card as plain text. The first line is the number of pairs. After that it is one number per line: space, mark, space, mark, all counted in 18 µs steps.

SD.remove("off.txt");
myFile = SD.open("off.txt", FILE_WRITE);
Serial.println("sd open ok \r\n");//dbg
if (myFile)
{
  myFile.println(counter);
// ...
for (uint8_t i = 0; i < currentpulse; i++) {
  // ...
  if (myFile) {
    myFile.println(pulses[i][0]);
  // ...
  if (myFile) {
    myFile.println(pulses[i][1]);
  }

IR_STATION_WITH_SD.ino, lines 534–562 (excerpt, // ... marks skipped lines)

This is the start of one of the files from my SD card (000.TXT). It starts with 72, so there are 72 pairs and 144 numbers after it. The file has 145 lines.

LineValueWhat it isTime (value × 18 µs)
172pair count-
231space558 µs
373mark1314 µs
421space378 µs
573mark1314 µs
621space378 µs
726mark468 µs
868space1224 µs
974mark1332 µs

Each count is stored in one byte (uint8_t pulses[120][2]), so a single value tops out at 255 steps, about 4.6 ms. A 9 ms mark would be 500 steps and does not fit in a byte.

Short: how the station saves a remote code to the SD card and plays it back.

Playback, and a 38 kHz carrier made in software

Playback runs the other way. In this version of the sketch, one radio command from the hub arms recording (it deletes off.txt), and another one plays off.txt back:

byte data[Mirf.payload] = {0};
while (!Mirf.dataReady()) {}; // wait for data to arrive
Mirf.getData(data);  // read to buffer
// ...
if (data[0] == 1 && data[1] == 1)
{
  Serial.println("Got AC Power on command - Sending....");
  // ...
  SD.remove("off.txt");
  coderecorded = false;
  updateRecLed();
// ...
else if (data[0] == 1 && data[1] == 0)
{
  Serial.println("Got AC Power off command - Sending....");
  // ...
  myFile = SD.open("off.txt");
  sendcode();

IR_STATION_WITH_SD.ino, lines 319–361 (excerpt, // ... marks skipped lines)

To play, sendcode() opens the file, reads the count, and loads every pair back into memory. It sends a fixed header first, a 9 ms mark and a 4.5 ms space. Then, for each pair, it waits out the space and pulses the LED for the mark.

pulseIR(9000);
delayMicroseconds(4500);

for (uint8_t i = 0; i < counter; i++)
{
  unsigned long t = (unsigned long)(pulses[i][0]) * RESOLUTION;
  if (t > 32000)
  {
    delay(t / 1000);
  }
  else
  {
    delayMicroseconds(t - RESOLUTION);
  }
  pulseIR((((unsigned long)pulses[i][1]) * RESOLUTION));
}

IR_STATION_WITH_SD.ino, lines 421–436

And that pulse is where the carrier comes from. There is no hardware timer: pulseIR() flips pin 7 by hand. On, wait 9 µs, off, wait 7 µs. Add the time digitalWrite() and the loop take, and the sketch counts 26 µs per cycle, which is roughly 38 kHz.

void pulseIR(long microsecs) {
  /***********
     we'll count down from the number of microseconds we are told to wait
  *************/

  // Serial.println("pulseIR microsecs");
  //   Serial.println(microsecs);

  while (microsecs > 0) {
    // 38 kHz is about 13 microseconds high and 13 microseconds low
    digitalWrite(IRledPin, HIGH);  // this takes about 3 microseconds to happen
    //   delayMicroseconds(8);         // hang out for 10 microseconds
    delayMicroseconds(9);         // hang out for 10 microseconds
    digitalWrite(IRledPin, LOW);   // this also takes about 3 microseconds
    //   delayMicroseconds(8);         // hang out for 10 microseconds
    delayMicroseconds(7);         // hang out for 10 microseconds

    // so 26 microseconds altogether
    microsecs -= 26;
  }
}

IR_STATION_WITH_SD.ino, lines 445–465

Short: a 3-pin IR receiver only gives you the envelope; a TV, an AC, anything with an IR remote listens for a 38 kHz carrier.

The IR LED driver (2N2222)

Pin 7 should not drive an IR LED hard on its own. An ATmega328 pin is rated 40 mA absolute maximum, and you do not want to live there. So the LED goes through a transistor. In this station the pin feeds the base of a 2N2222 through 1 kΩ, and the LED with a 68 Ω resistor sits between 5 V and the collector.

Schematic: digital output through 1 kilo-ohm to the base of a 2N2222, IR LED and 68 ohm resistor from plus 5 volts to the collector, emitter to ground
The IR LED driver used in the station (ir_transmit_2).
WhatHowAbout
Current from the pin (base)(5 V − ~0.7 V) / 1 kΩ4 mA
Current through the LED(5 V − ~1.3 V LED − a little for the transistor) / 68 Ω50 mA
Average LED currentthe 38 kHz carrier keeps it on about half the timeabout half of that

These currents are calculated from the schematic, not measured. A 2N2222 also switches far faster than 38 kHz, so it can follow the carrier.

The Fritzing in the repo shows a ready-made IR emitter module on the output. The station on the bench uses this 2N2222 driver.

Short: the 2N2222 driver for the IR LED. The currents are calculated, not measured.

Debugging on the bench

The envelope, on a logic analyzer

A 3-pin IR receiver demodulates the signal. What comes out of its pin is the envelope, the marks and spaces, without the 38 kHz carrier inside them. That is what the logic analyzer sees too. This is a 24 MHz capture in Saleae Logic 1.2.10, with the timing flags on the first long low pulse (2.648 ms):

Saleae Logic 1.2.10 showing an IR envelope on channel 0 with a timing marker reading 2.648 ms
The IR envelope in Saleae Logic, 24 MHz digital capture.

The same kind of signal as a clean drawing, a long start pulse and then the short bit pulses:

Drawing of an IR envelope: a long low start pulse followed by short pulses

And a whole frame on the Hantek scope at 10 ms per division: a start pulse, the data bits, a gap and a second burst.

Hantek 6022BE software showing an IR frame at 10 milliseconds per division
An IR frame in the Hantek 6022BE software, 10 ms/div.

Old play vs new play

I compared an old play capture to a new one. These are the serial dumps of printpulses(), in microseconds. Both decode as the same NEC command: address 0x00, command 0x40, then the repeat frame. The bits matched. The pulse timings differ by tens of microseconds, no pair by more than 90 µs. The one big difference is the idle time before the frame.

OldNew
Idle before the frame41,680 µs18,694 µs
Header mark9,252 µs9,324 µs
Header space4,500 µs4,428 µs
Address / command0x00 / 0x400x00 / 0x40
Repeat (gap, mark, space)40,086, 9,270, 2,214 µs40,068, 9,270, 2,214 µs

Decoded as NEC from the dump: the first byte pair is the address and its complement, the second the command and its complement. Both complement checks pass.

A bad recording

Sometimes the recording itself is dirty. In bad_ir.txt most of the pairs look like 1.67 ms and 0.58 ms. One pair reads 1926 µs / 324 µs, a glitch. Then the frame just stops: the dump ends after 25 bit pairs, with no repeat frame and no Close file ok line.

The 38 kHz carrier, on the scope

Here is what a logic analyzer on the receiver pin will not show you. Those receivers demodulate the signal, but the TV's receiver is still listening for a 38 kHz carrier. That is why playback has to put the carrier back.

On the Hantek, zoomed to 20 µs per division, the carrier shows up. The cursors read 26.7 µs, which is 37.45 kHz (the measurement table says 37.74 kHz):

Hantek 6022BE screenshot at 20 microseconds per division, cursor delta time 26.7 microseconds, frequency 37.45 kilohertz
The 38 kHz carrier, 20 µs/div, 4 MS/s. Cursors: ΔTime = 26.7 µs, 37.45 kHz.

A later capture reads 25.8 µs, 38.8 kHz:

Oscilloscope capture of a square wave carrier, cursor readout 25.8 microseconds, 38.8 kilohertz
A later carrier capture, 20 µs/div: 25.8 µs (38.8 kHz).

Both sit inside the window a 38 kHz receiver accepts. That is a working IR carrier.

Get the code

The full sketch is in the repo: IR_STATION_WITH_SD.ino (folder 26.07.17_IR_STATION_WITH_SD_INDICATION_LEDS_TV_WORKS in benchuk/SmartHomeDIY). The Fritzing file is in the same folder. The sketch credits Ladyada's raw IR decoder for the recording idea and the Arduino SD examples for the file handling.

If you build one, the parts are below. I would love to hear how it goes, and what you want to see next from the bench.