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.

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.
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 optimizeIR_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.
| Line | Value | What it is | Time (value × 18 µs) |
|---|---|---|---|
| 1 | 72 | pair count | - |
| 2 | 31 | space | 558 µs |
| 3 | 73 | mark | 1314 µs |
| 4 | 21 | space | 378 µs |
| 5 | 73 | mark | 1314 µs |
| 6 | 21 | space | 378 µs |
| 7 | 26 | mark | 468 µs |
| 8 | 68 | space | 1224 µs |
| 9 | 74 | mark | 1332 µ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.
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
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.
ir_transmit_2).| What | How | About |
|---|---|---|
| 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 current | the 38 kHz carrier keeps it on about half the time | about 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.
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):
The same kind of signal as a clean drawing, a long start pulse and then the short bit 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.
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.
| Old | New | |
|---|---|---|
| Idle before the frame | 41,680 µs | 18,694 µs |
| Header mark | 9,252 µs | 9,324 µs |
| Header space | 4,500 µs | 4,428 µs |
| Address / command | 0x00 / 0x40 | 0x00 / 0x40 |
| Repeat (gap, mark, space) | 40,086, 9,270, 2,214 µs | 40,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):
A later capture reads 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.