# IR Sensor

## Overview

![](https://cdn-learn.adafruit.com/assets/assets/000/001/083/medium800/light_IRsensorPNA4602_LRG.jpg?1396768527)

IR detectors are little microchips with a photocell that are tuned to listen to infrared light. They are almost always used for remote control detection - every TV and DVD player has one of these in the front to listen for the IR signal from the clicker. Inside the remote control is a matching IR LED, which emits IR pulses to tell the TV to turn on, off or change channels. IR light is not visible to the human eye, which means it takes a little more work to test a setup.

There are a few difference between these and say a [CdS Photocells](http://learn.adafruit.com/photocells):

- IR detectors are specially filtered for Infrared light, they are not good at detecting visible light. On the other hand, photocells are good at detecting yellow/green visible light, not good at IR light
- IR detectors have a **demodulator** inside that looks for modulated IR at 38 KHz. Just shining an IR LED wont be detected, it has to be PWM blinking at 38KHz. Photocells do not have any sort of demodulator and can detect any frequency (including DC) within the response speed of the photocell (which is about 1KHz)
- IR detectors are digital out - either they detect 38KHz IR signal and output low (0V) or they do not detect any and output high (5V). Photocells act like resistors, the resistance changes depending on how much light they are exposed to

In this tutorial we will show how to

- Test your IR sensor to make sure its working
- Read raw IR codes into a microcontroller
- Create a camera intervalometer
- Listen for 'commands' from a remote control on your microcontroller

## Some Stats

These stats are for the[IR detector in the Adafruit shop](http://www.adafruit.com/index.php?main_page=product_info&cPath=35&products_id=157 "Link: http://www.adafruit.com/index.php?main\_page=product\_info&cPath=35&products\_id=157") also known as PNA4602. Nearly all photocells will have slightly different specifications, although they all pretty much work the same. If there's a datasheet, you'll want to refer to it

- **Size:** square, 7mm by 8mm detector area
- **Output:** 0V (low) on detection of 38KHz carrier, 5V (high) otherwise
- **Sensitivity range:** 800nm to 1100nm with peak response at 940nm. Frequency range is 35KHz to 41KHz with peak detection at 38KHz
- **Power supply:** 3-5V DC 3mA
- **[PNA4602 Datasheet](http://learn.adafruit.com/system/assets/assets/000/010/139/original/PNA4602.pdf)** (now discontinued) or **[GP1UX311QS](http://learn.adafruit.com/system/assets/assets/000/010/140/original/GP1UX31QS.pdf)** or **[TSOP38238](http://learn.adafruit.com/system/assets/assets/000/010/141/original/tsop382.pdf)** (pin-compatible replacements)

&nbsp;

## What You Can Measure
![](https://cdn-learn.adafruit.com/assets/assets/000/000/548/medium800/light_irsensitive.gif?1447976090)

As you can see from these datasheet graphs, the peak frequency detection is at&nbsp; **38 KHz** &nbsp;and the peak LED color is&nbsp; **940 nm**. You can use from about 35 KHz to 41 KHz but the sensitivity will drop off so that it wont detect as well from afar. Likewise, you can use 850 to 1100 nm LEDs but they wont work as well as 900 to 1000nm so make sure to get matching LEDs! Check the datasheet for your IR LED to verify the wavelength.

Try to get a 940nm - remember that 940nm is not visible light (its Infra Red)!

# IR Sensor

## Testing an IR Sensor

Because there is a semiconductor/chip inside the sensor, it must be powered with 3 - 5V to function. Contrast this to photocells and FSRs where they act like resistors and thus can be simply tested with a multimeter.

![](https://cdn-learn.adafruit.com/assets/assets/000/000/549/medium800/light_pna4602pinout.gif?1447976100)

Here we will connect the detector as such:

- Pin 1 is the output so we wire this to a visible LED and resistor
- Pin 2 is ground
- Pin 3 is VCC, connect to 3-5V

When the detector sees IR signal, it will pull the output low, turning on the LED - since the LED is red its much easier for us to see than IR!

![](https://cdn-learn.adafruit.com/assets/assets/000/000/550/medium800/light_irremotetest.gif?1447976110)

We will use 4xAA 1.3V batteries (I use NiMH) so that the voltage powering the sensor is about 4V.

2 batteries (3V) may be too little. 3 Batteries should be fine if you have a triple-AA holder

You can also get 5V from a microcontroller like an Arduino if you have one around. Ground goes to the middle pin.

The positive (longer) head of the Red LED connects to the +6V pin and the negative (shorter lead) connects through a 200 to 1000 ohm resistor to the first pin on the IR sensor.

Now grab any remote control like for a TV, DVD, computer, etc. and point it at the detector while pressing some buttons, you should see the LED blink a couple times whenever the remote is pressed.

# IR Sensor

## IR Remote Signals

Now we know that the sensor works, we want to figure out whats being sent right? But before we do that let's first examine exactly how data is being sent from the IR remote (in your hand) to the IR receiving sensor (on the breadboard)

For this example we will use the Sony power on/off IR code from a Sony TV remote. Its very simple and commonly documented!

Lets pretend we have a Sony remote, and we can look at exactly what light is being blasted out of the IR LED. We'll hookup a basic light sensor (like a basic photocell!) and listen in. We won't use a decoder like a PNA4602 (just yet) because we want to see the undecoded signal. What we see is the following:

![](https://cdn-learn.adafruit.com/assets/assets/000/000/551/medium800/light_sonycodepulses.jpg?1396763963)

Basically we see pulses or IR signal. the yellow 'blocks' are when the IR LED is transmitting and when there is only a line, the IR LED is off. (Note that the voltage being at 3VDC is just because of the way I hooked up the sensor, if I had swapped the pullup for a pulldown it would be at ground.)

The first 'block' is about 2.5ms long (see the cursors and the measurement on the side)

If you zoom into one of those blocks…

![](https://cdn-learn.adafruit.com/assets/assets/000/000/552/medium800/light_sonycodepulsezoom.jpg?1396763967)

You see that they're not really 'blocks' but actually very fast pulses!

If you zoom in all the way…

![](https://cdn-learn.adafruit.com/assets/assets/000/000/553/medium800/light_sonycodepwm.jpg?1396763974)

You can measure the frequency of the IR pulses. As you can tell by the cursors and the measurements on the side, the frequency is about 37.04KHz

OK so now we can understand how IR codes are sent. The IR transmitter LED is quickly pulsed (PWM - pulse width modulated) at a high frequency of 38KHz and then that PWM is likewise pulsed on and off much slower, at times that are about 1-3 ms long.

Why not have the LED just on and off? Why have PWM 'carrier' pulsing? Many reasons!

One reason is that this lets the LED cool off. IR LEDs can take up to 1 Amp (1000 milliamps!) of current. Most LEDs only take 20mA or so. This means IR LEDs are designed for high-power blasting BUT they can only take it for a few microseconds. By PWM'ing it, you let the LED cool off half the time

Another reason is that the TV will only listen to certain frequencies of PWM. So a Sony remote at 37KHz wont be able to work with a JVC DVD player that only wants say 50KHz.

Finally, the most important reason is that by pulsing a carrier wave, you reduce the affects of ambient lighting. The TV only looks for changes in light levels that clock in around 37KHz. Just like its easier for us to tell differences between audio tones than to pin down the precsise pitch of a tone (well, for most people at least)

OK so now we know the carrier frequency. Its 37KHz. Next lets find the pulse widths!

Looking back at the first scope picture

![](https://cdn-learn.adafruit.com/assets/assets/000/000/554/medium800/light_sonycodepulses.jpg?1396763981)

The first pulse is 2.5ms. We can use the cursors to measure the remaining pulses. I'll spare you the 12 images and let you know that the pulses are:| **PWM ON** | **OFF** |
| 2.4 ms | 0.6 ms |
| 1.2 ms | 0.6 ms |
| 0.6 ms | 0.6 ms |
| 1.2 ms | 0.6 ms |
| 0.6 ms | 0.6 ms |
| 1.2 ms | 0.6 ms |
| 0.6 ms | 0.6 ms |
| 0.6 ms | 0.6 ms |
| 1.2 ms | 0.6 ms |
| 0.6 ms | 0.6 ms |
| 0.6 ms | 0.6 ms |
| 0.6 ms | 0.6 ms |
| 0.6 ms | 270 ms |

So lets say you don't have a $1000 oscilloscope, how else can you read these signals? Well the IR decoder such as the PNA4602 does us one favor, it 'filters out' the 38KHz signal so that we only get the big chunks of signal in the milliscond range. This is much easier for a microcontroller to handle. Thats what we'll do in the next section!# IR Sensor

## Using an IR Sensor

The good news is that it is very easy to hook up this sensor. Just connect the output to a digital pin. The bad news is that the Arduino's friendly&nbsp;**digitalRead()**&nbsp;procedure is a tad too slow to reliably read the fast signal as its coming in. Thus we use the hardware pin reading function directly from pin D2, that's what the line "IRpin\_PIN&nbsp;& BV(IRpin))" does. This trick is specific to ATmega328 based boards such as Arduino Uno, Adafruit Metro, etc.

### Adafruit METRO 328 Fully Assembled - Arduino IDE compatible

[Adafruit METRO 328 Fully Assembled - Arduino IDE compatible](https://www.adafruit.com/product/50)
We sure love the ATmega328 here at Adafruit, and we use them&nbsp;_a lot_&nbsp;for our own projects. The processor has plenty of GPIO, Analog inputs, hardware UART SPI and I2C, timers and PWM galore - just enough for most simple projects. When we need to go small, we use a <a...></a...>

Out of Stock
[Buy Now](https://www.adafruit.com/product/50)
[Related Guides to the Product](https://learn.adafruit.com/products/50/guides)
![Angled shot of a Adafruit METRO 328 Fully Assembled](https://cdn-shop.adafruit.com/640x480/50-09.jpg)

![](https://cdn-learn.adafruit.com/assets/assets/000/000/555/medium800/light_arduinopna4602.gif?1447976120)

https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/IR_Sensor/Arduino/Raw_IR/Raw_IR.ino

If you run this while pointing a Sony IR remote and pressing the ON button you will get the following...![](https://cdn-learn.adafruit.com/assets/assets/000/000/556/medium800/light_sonyread.gif?1447976130)

If you ignore the first OFF pulse (its just the time from when the Arduino turned on to the first IR signal received) and the last ON pulse (it the beginning of the next code) you'll find the Sony power code:| **PWM ON** | **OFF** |
| 2.5 ms | 0.6 ms |
| 1.2 ms | 0.6 ms |
| 0.6 ms | 0.6 ms |
| 1.2 ms | 0.6 ms |
| 0.6 ms | 0.6 ms |
| 1.2 ms | 0.6 ms |
| 0.6 ms | 0.6 ms |
| 0.6 ms | 0.6 ms |
| 1.2 ms | 0.6 ms |
| 0.6 ms | 0.6 ms |
| 0.6 ms | 0.6 ms |
| 0.6 ms | 0.6 ms |
| 0.6 ms | 27.2 ms |

# IR Sensor

## Making an Intervalometer

OK now that we can read IR codes, lets make a basic project. The first one we will do is to make an intervalometer. An intervalometer is basically a electronic thingy that makes a camera go off every few minutes or so. This can be used for timelapse projects or kite arial photography or other photo projects.![](https://cdn-learn.adafruit.com/assets/assets/000/000/589/medium800/light_invervalcam.jpeg?1396764320)

The camera we'll be using has an IR remote you can use to set it off (most higher-end cameras have these).![](https://cdn-learn.adafruit.com/assets/assets/000/000/590/medium800/light_canonremote.jpeg?1396764323)

First we will figure out the codes by reading the signal sent when the button is pressed. Then we'll take that data and make the Arduino spit out that code into an IR LED once a minute

OK step one is easy, point the remote control at the IR sensor and press the button, we got the following for our ML-L3 Nikon remote.

![](https://cdn-learn.adafruit.com/assets/assets/000/000/591/medium800/light_canonirread.gif?1447976274)

Looks like the data sent is:

| **PWM ON** | **OFF** |
| 2.0 ms | 27 ms |
| 0.4 ms | 1.5 ms |
| 0.5 ms | 3.5 ms |
| 0.5 ms | 62.2 ms |
| 2.0 ms | 27 ms |
| 0.5 ms | 1.5 ms |
| 0.5 ms | 3.5 ms |
| 0.5 ms |

If you look closely you'll see its actually just

| **PWM ON** | **OFF** |
| 2.0 ms | 27 ms |
| 0.4 ms | 1.5 ms |
| 0.5 ms | 3.5 ms |
| 0.5 ms | 62.2 ms |

sent twice. Sending the same signal twice is very common - doubling up to make sure it gets received

Next up we'll need to connect an IR 940nm LED to the output of the Arduino

![](https://cdn-learn.adafruit.com/assets/assets/000/000/592/medium800/light_intervalometer.gif?1447976285)

Then we'll write a sketch which will pulse pin #13 on and off very fast in the proper code sequence.https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/IR_Sensor/Arduino/Intervalometer/Intervalometer.ino

`void pulseIR(long microsecs)` is our helper procedure, it will create the PWM IR signal like we saw before. I used my scope to fine-tune it so that the delays added up right. We use the not-often-discussed&nbsp;`cli()`and&nbsp;`sei()`procedures to turn off interrupts. The Arduino does a couple things in the background like looking for serial data to read or write, keeping track of time, etc. Most of the time we can just ignore it but for delicate high speed signals like this we want to keep quiet so that we get a nice clean signal

If you look at `SendNikonCode()` you will see the IR command code that we deduced in the previous project by timing the pulses from the IR sensor.

![](https://cdn-learn.adafruit.com/assets/assets/000/000/593/medium800/light_intervalometer.jpeg?1396764351)

We wired this up and it worked great, make sure to point the IR LED at the camera properly.

# IR Sensor

## Reading IR Commands

For our final project, we will use a remote control to send messages to a microcontroller. For example, this might be useful for a robot that can be directed with an IR remote. It can also be good for projects that you want to control from far away, without wires.

For a remote in this example we'll be using an Apple clicker remote. You can use any kind of remote you wish, or you can steal one of these from an unsuspecting hipster.

![](https://cdn-learn.adafruit.com/assets/assets/000/000/594/medium800/light_appleremote.jpeg?1396764356)

We'll use the code from our previous sketch for raw IR reading but this time we'll edit our printer-outer to have it give us the pulses in a C array, this will make it easier for us to use for pattern matching.```
void printpulses(void) {
  Serial.println("\n\r\n\rReceived: \n\rOFF \tON");
  for (uint8_t i = 0; i &lt; currentpulse; i++) {
    Serial.print(pulses[i][0] * RESOLUTION, DEC);
    Serial.print(" usec, ");
    Serial.print(pulses[i][1] * RESOLUTION, DEC);
    Serial.println(" usec");
  }
 
  // print it in a 'array' format
  Serial.println("int IRsignal[] = {");
  Serial.println("// ON, OFF (in 10's of microseconds)");
  for (uint8_t i = 0; i &lt; currentpulse-1; i++) {
    Serial.print("\t"); // tab
    Serial.print(pulses[i][1] * RESOLUTION / 10, DEC);
    Serial.print(", ");
    Serial.print(pulses[i+1][0] * RESOLUTION / 10, DEC);
    Serial.println(",");
  }
  Serial.print("\t"); // tab
  Serial.print(pulses[currentpulse-1][1] * RESOLUTION / 10, DEC);
  Serial.print(", 0};");
}
```

I uploaded the new sketch and pressed the&nbsp; **Play** &nbsp;button on the Apple remote and got the following:

```
int IRsignal[] = { // ON, OFF (in 10's of microseconds) 
912, 438, 
68, 48, 
68, 158, 
68, 158, 
68, 158, 
68, 48, 
68, 158,  
68, 158,  
68, 158,  
70, 156,  
70, 158,  
68, 158,  
68, 48, 
68, 46,  
70, 46,  
68, 46,  
68, 160,  
68, 158,  
70, 46,  
68, 158,  
68, 46,  
70, 46,
68, 48,  
68, 46,  
68, 48,  
66, 48,  
68, 48,  
66, 160,  
66, 50,  
66, 160,  
66, 52,  
64, 160, 
66, 48,  
66, 3950,  
908, 214, 
66, 3012, 
908, 212, 
68, 0};
```

We'll try to detect that code.

Let's start a new sketch called&nbsp;**IR Commander&nbsp;(you can download the final code from GitHub at the green button below or click Download Project Zip in the complete code listing).&nbsp;**

[Open the GitHub repo for the code on this page](https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/master/IR_Sensor/Arduino/IR_Commander/ircommander.ino)
https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/IR_Sensor/Arduino/IR_Commander/IR_Commander.ino

https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/IR_Sensor/Arduino/IR_Commander/ircommander.h

This code uses parts of our previous sketch. The first part we'll do is to create a function that just listens for an IR code an puts the pulse timings into the&nbsp;**pulses[]**&nbsp;array. It will return the number of pulses it heard as a return-value.

```
int listenForIR(void) {
  currentpulse = 0;
 
  while (1) {
    uint16_t highpulse, lowpulse;  // temporary storage timing
    highpulse = lowpulse = 0; // start out with no pulse length
 
//  while (digitalRead(IRpin)) { // this is too slow!
    while (IRpin_PIN &amp; (1 &lt;&lt; IRpin)) {
       // pin is still HIGH
 
       // count off another few microseconds
       highpulse++;
       delayMicroseconds(RESOLUTION);
 
       // If the pulse is too long, we 'timed out' - either nothing
       // was received or the code is finished, so print what
       // we've grabbed so far, and then reset
       if ((highpulse &gt;= MAXPULSE) &amp;&amp; (currentpulse != 0)) {
         return currentpulse;
       }
    }
    // we didn't time out so lets stash the reading
    pulses[currentpulse][0] = highpulse;
 
    // same as above
    while (! (IRpin_PIN &amp; _BV(IRpin))) {
       // pin is still LOW
       lowpulse++;
       delayMicroseconds(RESOLUTION);
       if ((lowpulse &gt;= MAXPULSE)  &amp;&amp; (currentpulse != 0)) {
         return currentpulse;
       }
    }
    pulses[currentpulse][1] = lowpulse;
 
    // we read one high-low pulse successfully, continue!
    currentpulse++;
  }
}
```

Our new&nbsp;**loop()**&nbsp;will start out just listening for pulses

```
void loop(void) {
  int numberpulses;
 
  numberpulses = listenForIR();
 
  Serial.print("Heard ");
  Serial.print(numberpulses);
  Serial.println("-pulse long IR signal");
}
```

When we run this it will print out something like...![](https://cdn-learn.adafruit.com/assets/assets/000/000/595/medium800/light_pulsecounter.gif?1447976294)

OK time to make the sketch compare what we received to what we have in our stored array:![](https://cdn-learn.adafruit.com/assets/assets/000/000/596/medium800/light_ircompare.gif?1447976302)

As you can see, there is some variation. So when we do our comparison we can't look for preciesely the same values, we have to be a little 'fuzzy'. We'll say that the values can vary by 20% - that should be good enough.```
// What percent we will allow in variation to match the same code \\ #define FUZZINESS 20
 
void loop(void) {
  int numberpulses;
 
  numberpulses = listenForIR();
 
  Serial.print("Heard ");
  Serial.print(numberpulses);
  Serial.println("-pulse long IR signal");
 
  for (int i=0; i&lt; numberpulses-1; i++) {
    int oncode = pulses[i][1] * RESOLUTION / 10;
    int offcode = pulses[i+1][0] * RESOLUTION / 10;
 
    Serial.print(oncode); // the ON signal we heard
    Serial.print(" - ");
    Serial.print(ApplePlaySignal[i*2 + 0]); // the ON signal we want 
 
    // check to make sure the error is less than FUZZINESS percent
    if ( abs(oncode - ApplePlaySignal[i*2 + 0]) &lt;= (oncode * FUZZINESS / 100)) {
      Serial.print(" (ok)");
    } else {
      Serial.print(" (x)");
    }
    Serial.print("  \t"); // tab
 
    Serial.print(offcode); // the OFF signal we heard
    Serial.print(" - ");
    Serial.print(ApplePlaySignal[i*2 + 1]); // the OFF signal we want 
 
    if ( abs(offcode - ApplePlaySignal[i*2 + 1]) &lt;= (offcode * FUZZINESS / 100)) {
      Serial.print(" (ok)");
    } else {
      Serial.print(" (x)");
    }
 
    Serial.println();
  }
}
```

![](https://cdn-learn.adafruit.com/assets/assets/000/000/597/medium800/light_codecompareok.gif?1447976311)

This loop, as it goes through each pulse, does a little math. It compares the absolute (**abs()**) difference between the code we heard and the code we're trying to match abs(oncode - ApplePlaySignal[i\*2 + 0]) and then makes sure that the error is less than FUZZINESS percent of the code length (oncode \* FUZZINESS / 100)

We found we had to tweak the stored values a little to make them match up 100% each time. IR is not a precision-timed protocol so having to make the FUZZINESS 20% or more is not a bad thing

Finally, we can turn the&nbsp;**loop()**&nbsp;into its own function which will return&nbsp; **true** &nbsp;or&nbsp; **false** &nbsp;depending on whether it matched the code we ask it to. We also commented out the printing functions

```
boolean IRcompare(int numpulses, int Signal[]) {
 
  for (int i=0; i&lt; numpulses-1; i++) {
    int oncode = pulses[i][1] * RESOLUTION / 10;
    int offcode = pulses[i+1][0] * RESOLUTION / 10;
 
    /*
    Serial.print(oncode); // the ON signal we heard
    Serial.print(" - ");
    Serial.print(Signal[i*2 + 0]); // the ON signal we want 
    */
 
    // check to make sure the error is less than FUZZINESS percent
    if ( abs(oncode - Signal[i*2 + 0]) &lt;= (Signal[i*2 + 0] * FUZZINESS / 100)) {
      //Serial.print(" (ok)");
    } else {
      //Serial.print(" (x)");
      // we didn't match perfectly, return a false match
      return false;
    }
 
    /*
    Serial.print("  \t"); // tab
    Serial.print(offcode); // the OFF signal we heard
    Serial.print(" - ");
    Serial.print(Signal[i*2 + 1]); // the OFF signal we want 
    */
 
    if ( abs(offcode - Signal[i*2 + 1]) &lt;= (Signal[i*2 + 1] * FUZZINESS / 100)) {
      //Serial.print(" (ok)");
    } else {
      //Serial.print(" (x)");
      // we didn't match perfectly, return a false match
      return false;
    }
 
    //Serial.println();
  }
  // Everything matched!
  return true;
}
```

We then took more IR command data for the 'rewind' and 'fastforward' buttons and put all the code array data into&nbsp; **ircodes.h&nbsp;** to keep the main sketch from being too long and unreadable&nbsp;[(you can get all the code from github)](http://github.com/adafruit/IR-Commander)

Finally, the main loop looks like this:

```
void loop(void) {
  int numberpulses;
 
  numberpulses = listenForIR();
 
  Serial.print("Heard ");
  Serial.print(numberpulses);
  Serial.println("-pulse long IR signal");
  if (IRcompare(numberpulses, ApplePlaySignal)) {
    Serial.println("PLAY");
  }
    if (IRcompare(numberpulses, AppleRewindSignal)) {
    Serial.println("REWIND");
  }
    if (IRcompare(numberpulses, AppleForwardSignal)) {
    Serial.println("FORWARD");
  }
}
```

We check against all the codes we know about and print out whenever we get a match. You could now take this code and turn it into something else, like a robot that moves depending on what button is pressed.

After testing, success!

![](https://cdn-learn.adafruit.com/assets/assets/000/000/598/medium800/light_mulitirbutton.gif?1447976321)

# IR Sensor

## CircuitPython

With CircuitPython you can easily read IR sensor pulses from Python code. &nbsp;Built-in to CircuitPython is a special `pulseio` module which actually does most of the work of reading fast IR receiver pulses for you. &nbsp;Even better with Python code you can very easily store and manipulate large lists of pulse lengths.&nbsp; There's even a handy [Adafruit CircuitPython IRRemote](https://github.com/adafruit/Adafruit_CircuitPython_IRRemote) module which simplifies some of the processing logic for reading generic remote controls.&nbsp; CircuitPython makes it very easy to read IR signals!

# Hardware & Setup

To read raw IR signals you'll need to connect an IR sensor to your board as shown on the previous pages. &nbsp;In this example we'll assume the sensor output is connected to pin D2 on your board.

As mentioned you'll also need to install the [Adafruit CircuitPython IRRemote](https://github.com/adafruit/Adafruit_CircuitPython_IRRemote) library on your CircuitPython board.

First make sure you are running the&nbsp;[latest version of Adafruit CircuitPython](../../../../welcome-to-circuitpython/installing-circuitpython)&nbsp;for your board.

Next you'll need to install the necessary libraries&nbsp;to use the hardware--carefully follow the steps to find and install these libraries from&nbsp;[Adafruit's CircuitPython library bundle](https://github.com/adafruit/Adafruit_CircuitPython_Bundle).&nbsp; Our introduction guide has&nbsp;[a great page on how to install the library bundle](../../../../welcome-to-circuitpython/circuitpython-libraries)&nbsp;for both express and non-express boards.

Remember for non-express boards like the, you'll need to manually install the necessary libraries from the bundle:

- **adafruit\_irremote.mpy**

Or download the file from the latest release on the [Adafruit CircuitPython IRRemote releases page](https://github.com/adafruit/Adafruit_CircuitPython_IRRemote/releases).&nbsp;

Before continuing make sure your board's lib folder or root filesystem has the&nbsp; **adafruit\_irremote.mpy&nbsp;** module&nbsp;copied over.

# Usage

Next&nbsp;[connect to the board's serial REPL&nbsp;](../../../../welcome-to-circuitpython/the-repl)so you are at the CircuitPython&nbsp; **\>\>\>** &nbsp;prompt.

Then import the necessary **board** and **pulseio** modules:

```
import board
import pulseio
```

Now create an instance of the [PulseIn class](http://circuitpython.readthedocs.io/en/latest/shared-bindings/pulseio/PulseIn.html) which reads pulses from the IR sensor's output. &nbsp;A pulse is simply a change from high to low or vice-versa and the PulseIn class will record the microsecond duration of each pulse. &nbsp;Let's create a pulse input that can remember the duration of up to 200 pulses (enough to record most remote control codes):

```
pulses = pulseio.PulseIn(board.D2, maxlen=200, idle_state=True)
```

Let's break down all the parameters passed in to the PulseIn initializer:

- **Board pin** - This is a required parameter which indicates which pin is connected to the output of the IR receiver.
- **maxlen** - This specifies the number of pulse durations to record. &nbsp;For most remote controls a value of 200 will be more than enough pulse durations to store. &nbsp;If you set this too high you might use more memory than your board has available so be careful with what value you pick.
- **idle\_state** - This is a boolean that indicates the 'default' or idle state of the pulse pin. &nbsp;For IR receivers they typically idle in a high logic or True state so setting the idle\_state to True indicates the normal state is high logic level.

Once you have a pulse input object you can interact with it as if it were a list of duration values. &nbsp;Internally the PulseIn class is always listening for pulses from the pin (i.e. a change from the current high/low logic level to the opposite level) and saving the duration of the pulse. &nbsp;You can list then number of received pulses just like reading the length of a list:

```
len(pulses)
```

![](https://cdn-learn.adafruit.com/assets/assets/000/047/691/medium800/light_Screen_Shot_2017-10-26_at_5.07.20_PM.png?1509062868)

A value of zero means the sensor hasn't yet received a pulse. &nbsp;Try pointing a remote control at the sensor and pressing a button. &nbsp;Then read the pulse length again:

```
len(pulses)
```

![](https://cdn-learn.adafruit.com/assets/assets/000/047/692/medium800/light_Screen_Shot_2017-10-26_at_5.10.29_PM.png?1509063054)

Now we have some pulse durations to investigate! &nbsp;First let's tell the pulse class to temporarily stop listening for pulses. &nbsp;This is useful so that you can operate on the last seen pulse without other pulses adding more noise or artifacts:

```
pulses.pause()
```

Now investigate some of the pulse durations by reading values as if the pulse object were a list. &nbsp;For example to read the first three durations:

```
pulses[0]
pulses[1]
pulses[2]
```

![](https://cdn-learn.adafruit.com/assets/assets/000/047/693/medium800/light_Screen_Shot_2017-10-26_at_5.13.38_PM.png?1509063242)

Each duration is the time in milliseconds that the pulse was at a specific logic level. &nbsp;The very first pulse is a maximum value of 65535 because it represents the amount of time the sensor was waiting for the pulse to start (i.e. how long it was in the default high logic level idle state). &nbsp;Just like with the Arduino code on the previous page you can ignore this first value.

The next two values are interesting, the next pulse value&nbsp;shows the sensor received a pulse that was about 9 milliseconds long (or ~9000 microseconds). &nbsp;Then the sensor received no pulse for about 4 milliseconds. &nbsp;This pair of values represents a single pulse and the start of the remote control signal. &nbsp;It's good to see a value of ~9ms on and ~4m off as that's a common preamble or start for IR codes!

It turns out these pairs of pulses are so common between different remote controls that many of them can be read with similar code.&nbsp; The Adafruit CircuitPython IRRemote library is a very simple IR remote control decoding library that simplifies much of the pulse and remote decoding logic.&nbsp; Let's use this module to simplify our pulse analysis, first import it and then create a remote decoder:

```
import adafruit_irremote
decoder = adafruit_irremote.GenericDecode()
```

![](https://cdn-learn.adafruit.com/assets/assets/000/047/881/medium800/light_Screen_Shot_2017-11-02_at_2.36.24_PM.png?1509658601)

The decoder class allows you to easily wait for and read a list of pulses from a remote control press.&nbsp; Before you use it lets turn the pulse input back on (remember it's currently paused) and clear its previous input:

```
pulses.clear()
pulses.resume()
```

![](https://cdn-learn.adafruit.com/assets/assets/000/047/882/medium800/light_Screen_Shot_2017-11-02_at_2.39.09_PM.png?1509658767)

Now we're ready to use the decoder to wait for and return pulses.&nbsp; Run this code and notice the REPL stops and waits for further input:

```
pulse = decoder.read_pulses(pulses)
```

![](https://cdn-learn.adafruit.com/assets/assets/000/047/883/medium800/light_Screen_Shot_2017-11-02_at_2.41.12_PM.png?1509658896)

Aim your remote control at the receiver and press a button.&nbsp; You should see the REPL return to normal operation.&nbsp; This means the decoder was able to detect an IR remote signal and returned the raw list of pulse values.

![](https://cdn-learn.adafruit.com/assets/assets/000/047/885/medium800/light_Screen_Shot_2017-11-02_at_2.43.00_PM.png?1509658994)

This list of pulses is an array which contains the length in microseconds of each high and low pulse from the receiver.&nbsp; For example you can check how many pulse changes were detected and see their lengths by using the standard array length and printing operations:

```
len(pulse)
pulse
```

![](https://cdn-learn.adafruit.com/assets/assets/000/047/886/medium800/light_Screen_Shot_2017-11-02_at_2.44.44_PM.png?1509659102)

One very useful thing the decoder is doing internally is detecting and ignoring noise or extraneous pulse widths, like a long starting pulse width before the remote control is detected.&nbsp; This is very useful as it simplifies your IR processing code--you can focus on just looking at the 'cleaned up' pulse lengths!

Try recording a second pulse:

```
pulse2 = decoder.read_pulses(pulses)
```

![](https://cdn-learn.adafruit.com/assets/assets/000/047/887/medium800/light_Screen_Shot_2017-11-02_at_2.48.47_PM.png?1509659351)

Remember the **read\_pulses** function will wait for a remote control press to be detected (or if one had previously happened and not been processed it will grab it instead).&nbsp; Press the same button on the remote to generate a similar pulse as the first press:

![](https://cdn-learn.adafruit.com/assets/assets/000/047/888/medium800/light_Screen_Shot_2017-11-02_at_2.50.42_PM.png?1509659477)

Now let's compare the first and second pulse list to see if they match.&nbsp; A simple comparison might be to check every single value in each list and verify they're the same.&nbsp; Let's try it with a simple Python function we define:

```
def simple_pulse_compare(pulse1, pulse2):
    if len(pulse1) != len(pulse2):
        return False
    for i in range(len(pulse1)):
        if pulse1[i] != pulse2[i]:
            return False
    return True

simple_pulse_compare(pulse, pulse2)
```

![](https://cdn-learn.adafruit.com/assets/assets/000/047/889/medium800/light_Screen_Shot_2017-11-02_at_3.00.02_PM.png?1509660020)

Oh no, the comparison failed and returned false!&nbsp; What happened, wasn't the same button pressed?&nbsp; It turns out the timing between pulses can vary in small ways.&nbsp; If you look at the individual pulse lengths of each array you'll see they're close but not exactly the same.&nbsp; If you compare raw pulses you need to add a 'fuzzyness' that compares values that are close but not exactly the same.

Let's make a new fuzzy compare function that will check for pulses that are close to each other (within 20% of one another for example):

```
def fuzzy_pulse_compare(pulse1, pulse2, fuzzyness=0.2):
    if len(pulse1) != len(pulse2):
        return False
    for i in range(len(pulse1)):
        threshold = int(pulse1[i] * fuzzyness)
        if abs(pulse1[i] - pulse2[i]) &gt; threshold:
            return False
    return True

fuzzy_pulse_compare(pulse, pulse2)
```

![](https://cdn-learn.adafruit.com/assets/assets/000/047/890/medium800/light_Screen_Shot_2017-11-02_at_3.06.18_PM.png?1509660396)

Success!&nbsp; Both pulses appear to be the same when using a fuzzy comparison.&nbsp; By default the comparison will consider pulses the same if they're within 20% of each other, but you can change that fuzzyness by setting the fuzzyness keyword to a different value.&nbsp;&nbsp;The fuzzyness value is a percentage from 0 to 1.0 (or 0 to 100%) where the pulses must be within that percent of each other's timing.&nbsp; Lower values are stricter and require more similar pulses, whereas higher values are less strict and might allow noise or incorrect pulses to appear the same.&nbsp; In general stick with the 20% fuzzyness unless you run into more problematic IR signals.

Let's tie everything together by making a complete program that waits for the button above to be pressed and prints a message.&nbsp;

You can use the recorded pulse&nbsp;list in your program to remember the previously recorded pulse and compare new ones against it.&nbsp; To detect a different&nbsp;key press just record it with the steps above and update the pulse&nbsp;list in the code.&nbsp;

Change the **pulse** &nbsp;list at the top in the code below to the value you recorded (just copy and paste it from the REPL) and save it as a **code.py** on your board:

[Download the IR CircuitPython Example](https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/master/IR_Sensor/CircuitPython/IR.py)
https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/IR_Sensor/CircuitPython/code.py

Now when you press the remote control button you should see a message printed at the REPL!&nbsp; That's all there is to basic raw IR pulse detection and comparison with CircuitPython! &nbsp;

The code on this page can be handy for basic or unknown remote control protocol detection. However be aware that remote controls are actually quite advanced and sometimes don't behave the way you expect--like pressing a button multiple times might not actually send the full code each time, instead the remote might send a shorter repeat code! &nbsp;This means the basic raw IR detection shown here could fail because it doesn't expect a repeat code when one is seen. &nbsp;

It turns out general IR remote detection is so advanced it's best handled by a separate library which can decode repeat codes and more. &nbsp;For CircuitPython check out the [IRLibCP module](https://github.com/adafruit/IRLibCP) from Chris Young, it has much more full featured IR remote decoding support!

# IR Sensor

## Python Docs


## Featured Products

### Adafruit METRO 328 Fully Assembled - Arduino IDE compatible

[Adafruit METRO 328 Fully Assembled - Arduino IDE compatible](https://www.adafruit.com/product/50)
We sure love the ATmega328 here at Adafruit, and we use them&nbsp;_a lot_&nbsp;for our own projects. The processor has plenty of GPIO, Analog inputs, hardware UART SPI and I2C, timers and PWM galore - just enough for most simple projects. When we need to go small, we use a <a...></a...>

Out of Stock
[Buy Now](https://www.adafruit.com/product/50)
[Related Guides to the Product](https://learn.adafruit.com/products/50/guides)
### IR (Infrared) Receiver Sensor

[IR (Infrared) Receiver Sensor](https://www.adafruit.com/product/157)
IR sensor tuned to 38KHz, perfect for receiving commands from a TV remote control. Runs at 3V to 5V so it's great for any microcontroller.  
  
To use, connect pin 3 (all the way to the right) to 5V power, pin 2 (middle) to ground and listen on pin 1. It doesn't do any decoding...

In Stock
[Buy Now](https://www.adafruit.com/product/157)
[Related Guides to the Product](https://learn.adafruit.com/products/157/guides)
### Super-bright 5mm IR LED

[Super-bright 5mm IR LED](https://www.adafruit.com/product/387)
Infrared LEDs are used for remote controls (they're the little LED in the part you point at your TV) and 'night-vision' cameras, and these little blue guys are high powered ones! They are 940nm wavelength, which is what nearly all devices listen to. They're 20 degree beamwidth,...

In Stock
[Buy Now](https://www.adafruit.com/product/387)
[Related Guides to the Product](https://learn.adafruit.com/products/387/guides)
### Mini Remote Control

[Mini Remote Control](https://www.adafruit.com/product/389)
This little remote control would be handy for controlling a robot or other project from across the room. It has 21 buttons and a layout we thought was handy: directional buttons and number entry buttons. The remote uses the NEC encoding type and sends data codes 0 thru 26 (it skips #3, #7,...

In Stock
[Buy Now](https://www.adafruit.com/product/389)
[Related Guides to the Product](https://learn.adafruit.com/products/389/guides)
### Super-bright 5mm IR LED (25 pack)

[Super-bright 5mm IR LED (25 pack)](https://www.adafruit.com/product/388)
Infrared LEDs are used for remote controls (they're the little LED in the part you point at your TV) and 'night-vision' cameras, and these little blue guys are high powered ones! They are 940nm wavelength, which is what nearly all devices listen to. They're 20 degree beamwidth,...

In Stock
[Buy Now](https://www.adafruit.com/product/388)
[Related Guides to the Product](https://learn.adafruit.com/products/388/guides)
### Adafruit METRO 328 - Arduino Compatible - with Headers

[Adafruit METRO 328 - Arduino Compatible - with Headers](https://www.adafruit.com/product/2488)
This is the&nbsp; **Adafruit METRO Arduino-Compatible - with&nbsp;headers.&nbsp;** It's a fully assembled and tested microcontroller and physical computing board with through-hole headers attached.&nbsp; If you don't want a&nbsp;Metro with the headers attached for...

Out of Stock
[Buy Now](https://www.adafruit.com/product/2488)
[Related Guides to the Product](https://learn.adafruit.com/products/2488/guides)

## Related Guides

- [Mini Thermal Receipt Printers](https://learn.adafruit.com/mini-thermal-receipt-printer.md)
- [Experimenter's Guide for Metro](https://learn.adafruit.com/experimenters-guide-for-metro.md)
- [Introducing Adafruit Trellis ](https://learn.adafruit.com/adafruit-trellis-diy-open-source-led-keypad.md)
- [Ladyada's Learn Arduino - Lesson #0](https://learn.adafruit.com/ladyadas-learn-arduino-lesson-number-0.md)
- [Ladyada's Learn Arduino - Lesson #1](https://learn.adafruit.com/ladyadas-learn-arduino-lesson-number-1.md)
- [Multi-tasking the Arduino - Part 1](https://learn.adafruit.com/multi-tasking-the-arduino-part-1.md)
- [Arduino Lesson 13. DC Motors](https://learn.adafruit.com/adafruit-arduino-lesson-13-dc-motors.md)
- [How to program a Zumo Robot with Simulink](https://learn.adafruit.com/zumo-robot-control-with-simulink.md)
- [Arduino Lesson 12. LCD Displays - Part 2](https://learn.adafruit.com/adafruit-arduino-lesson-12-lcd-displays-part-2.md)
- [Digital Circuits 7: MCUs... how do they work?](https://learn.adafruit.com/mcus-how-do-they-work.md)
- [Animating Multiple LED Backpacks](https://learn.adafruit.com/animating-multiple-led-backpacks.md)
- [Adafruit  PCA9685 16-Channel Servo Driver](https://learn.adafruit.com/16-channel-pwm-servo-driver.md)
- [TTL Serial Camera](https://learn.adafruit.com/ttl-serial-camera.md)
- [Sending an SMS with Temboo](https://learn.adafruit.com/sending-an-sms-with-temboo.md)
- [How to Choose a Microcontroller](https://learn.adafruit.com/how-to-choose-a-microcontroller.md)
