Introduction: Using Infrared Sensor With Arduino

Picture of Using Infrared Sensor With Arduino

What is an infrared (aka IR) sensor?

An IR sensor is an electronic instrument that scans IR signals in specific frequency ranges defined by standards and converts them to electric signals on its output pin (typically called signal pin). The IR signals are mainly used for transmitting commands over the air on short distances (typically few meters) like what you’ve already worked with on TV remote controls or other similar electronic devices.


IR communication protocol

Each signal represents a specific code. Electric signals can be converted back to the actual data/code that sender has sent. When you press a button on your TV remote control, it generates a signal corresponding to the button code (e.g. On/Off, Volume Up, etc.) and sends it for a receiver (in this case your TV). Both sender and receiver agreed on a set of codes so that receiver knows what to do based on each code. The way a code should be modulated (modeled) as a signal is defined in different standard and each sensor manufacturer normally tries to produce a product compatible with them so that it could be used in different devices. One of the most known standard protocols is from NEC. You can find a brief history of IR protocols on Wikipedia under Consumer IR title.

Step 1: How an IR Sensor Looks Like?

Picture of How an IR Sensor Looks Like?

IR sensors are available on different packages. Here you can see some typical packaging for an IR receiver.

Step 2: IR Sensor Breakout Board/module

Picture of IR Sensor Breakout Board/module

You can also buy them as an IR module/breakout board on eBay, Aliexpress or Amazon. Such modules normally incorporate one of the sensors mentioned above with a nice breadboard friendly package together with an LED that would flash when the sensor detects a signal. By doing so you would notice if any data is being transferred. I highly suggest starting with one of these modules.

Note: if you have a raw IR sensor, nothing would change, except that you should check the datasheet of the sensor to make sure you’re wiring it correctly because otherwise you may have a beautiful blue smoke with a smell that would last for an hour. You know what I mean ;)

Step 3: Required Parts and Components

Picture of Required Parts and Components

Here you can find the list of components that you would need to complete this tutorial:

eBay links:

Amazon.com links:

Amazon.co.uk links:

Step 4: Connecting IR Sensor to Arduino

Picture of Connecting IR Sensor to Arduino

Setting up IR sensor connection to Arduino is very simple. Beside VCC and GND pin, the sensor has only one output pin that should be connected to one of digital pins of the Arduino. In this case it’s connected to pin 13.

I tried to demonstrate both IR sensor module and raw IR sensor setup. As can be seen on pictures, the position of the VCC and GND pins on the sensor module is the opposite of the raw sensor. However it may not be the case for your sensor, so as mentioned in previous step, in case of using the raw sensor, check the datasheet first.

Step 5: Find the Code Corresponding to Each Key on the Remote

Picture of Find the Code Corresponding to Each Key on the Remote

In order to program Arduino to do something when you press a key on the remote, you should first have the code corresponding to that key. The key code is a number normally presented as hexadecimal. Each remote controller has its own set of key codes while it’s possible that two controllers share the same code for different purposes. Having different key codes along with using different frequency ranges, ensures that two remote controllers of different devices would not have interference. That’s why when you change your TV channel, your DVD player doesn’t react at all.

To detect the codes for your IR remote, you have to first run a simple sketch that tries to read the code from sensor when you press a key and sends that via the serial port to your computer where you can access it using Serial Monitor tools of Arduino IDE. This is what the sketch attached to this section does. It would be better to press every button in order see the code and write down the list of codes somewhere so that you would not need to run this code again in future. The list of key codes you see as a table in the picture are actually codes I received when pressing buttons on my cheap IR remote.

You can also access the actual source code shared on my Arduino web editor at ir-key-code-logger.

Note: Don't get afraid if you see a code like FFFFFF somewhere in between. It means you have pressed and hold a button for a while. We'll get back into it later on. For now just ignore them and focus on other codes.

Step 6: Control a Set of LEDs Using IR Remote

Picture of Control a Set of LEDs Using IR Remote

Now that we have a code for each button, it's time to focus on the way we can use them. Normally you use the IR remote to send commands to Arduino to do something like turning on or off a lamp, move a robot in specific direction, display something on an LCD/OLED screen, etc. Here we try to demonstrate the process using a simple circuit consisting of 4 LEDs in different colors. We want to turn each one of them on or off by a dedicated button of the IR remote. As you can see on the schematic, you have to connect the Arduino in the following way to LEDs and sensor:

Arduino GND -> IR sensor GND.

Arduino VCC -> IR sensor VCC.

Arduino 13 -> IR sensor signal output.

Arduino 2 -> Anode of the blue LED (shorter pin of the blue LED)

Arduino 3 -> Anode of the green LED (shorter pin of the green LED)

Arduino 4 -> Anode of the yellow LED (shorter pin of the yellow LED)

Arduino 5 -> Anode of the red LED (shorter pin of the red LED)

Arduino GND -> Cathode of all LEDs via a 220 ohm resistor (longer pin of the LEDs)

You can find the code corresponding to this circuit in the attached file or on my Arduino web editor at ir-led-control.

Step 7: Troubleshooting

While setting up your project and following the steps you may encounter many weird situations. Here is the list of some common errors that you may get when working with IR sensor.


Getting FFFFFF when pressing a key

When pressing a button you may notice that most of the time it reports a code like FFFFFF. This happens when you press a button and hold it for a while, even for a short period of time. The scenario is that when you press the button initially, IR remote sends the button code and as long as you hold the button, it repeats sending FFFFFF which means that user is still pressing the button reported recently. That would be OK. You can just omit them. The actual code is the one you got right before FFFFFF on the Serial Monitor.


IR Sensor doesn't react at all and seems it's getting warm!

Cut the power!!! If you're sure that the key code logger sketch is correct, then the problem maybe due to the wrong setup of your wires. The scenario that happened to me was that for my IR module (the one attached to the board) I had connected the VCC and GND in the opposite way (due to not using a proper colors for my hookup wires). By doing so the sensor component burned and a nice blue smoke raised. I bought a pack of raw IR sensors and tried to replace it and now it works like a charm :). Unfortunately I did the same mistake when I was testing with the raw IR sensor and this time nothing happened except that the sensor got warm. So always check the circuit before turning on the power!


Sometimes the sensor detects a code that I've never seen before

This is one of the most common issues. It's most likely due to one of the following reasons:

  • You're not pointing your IR remote directly toward the sensor

This will lead to having some new codes (mostly longer codes) that you've never received before and normally doesn't match with the length of the codes you already have. So remember to always point the remote towards your sensor.

  • You're using a cheap IR remote (like the one I used in this tutorial)

Instead of using a cheap unpredictable remotes, you can try the same scenario using your TV or DVD Player remote control or an IR remote of any devices you have. They normally have a good signal/hardware quality (and of course are more expensive) and based on my experience, they normally work well even if you don't point your remote directly toward the sensor.


How do I know if a code that is logged is not a garbage

The codes are normally presented in hexadecimal format. If you convert them to the corresponding binary value, you'll notice that the binary representation of the last byte is the negation of the byte comes before that. If you know this, you can do this check in your code to make sure that the code you received is actually a valid one or not. As an example, if you got FF7A85 its binary representation would be as below:

1111 1111 0111 1010 1000 0101

From left to right, each batch of 4 digits are representation of a character in the original hexadecimal number. As you can see, the batch corresponding to 7 is 0111 and the batch corresponding to 8 is 1000 which is the exact negation of it. By negation I mean all 0s would be 1s and all 1s would be replaced by 0s. The same is true for the next one which is A (1010) and 5 (0101).

Step 8: What to Do Next?

Now it's your turn. It's all up to your imagination to see what you can do with this little simple sensor in your hand. Here are some ideas to begin with:

  • Use the IR remote control of one of the devices you have at home (TV, Stereo, etc.) and try to use it in your Arduino project
  • Try to turn on all LEDs at once by pressing a key and then turn them off using another key
  • Use Up/Down button of the remote to turn LEDs on/off one by one until all of them turn on/off
  • Create a traffic light using LEDs and control it using your remote
  • If you have a small DC motor at hand, try to start/stop or change its rotation direction via IR remote
  • You can use your TV remote to control your robot or enable/disable some sensors/actuators on it

Let me know on comments, what would you do (or you've already done) using IR remote.

Comments

PrakharT1 (author)2017-09-30

I am getting these error pls help

Arduino: 1.8.3 (Windows 10), Board: "Arduino/Genuino Uno"

C:\Program Files (x86)\Arduino\libraries\RobotIRremote\src\IRremoteTools.cpp:5:16: error: 'TKD2' was not declared in this scope

int RECV_PIN = TKD2; // the pin the IR receiver is connected to

^

exit status 1

Error compiling for board Arduino/Genuino Uno.

This report would have more information with

"Show verbose output during compilation"

option enabled in File -> Preferences.

zaerymoghaddam (author)PrakharT12017-09-30

Hi Prakhar

It's not easy to say exactly what's the problem. But based on the error message, looks like a compilation issue regarding variable TKD2. Can you post your complete code or at least more than a single line to inspect it more?

PrakharT1 (author)zaerymoghaddam2017-10-01

/**

* Copyright (c) 2017 Ehsan Zaery Moghaddam (zaerymoghaddam@gmail.com)

*

* Permission is hereby granted, free of charge, to any person obtaining a copy

* of this software and associated documentation files (the "Software"), to deal

* in the Software without restriction, including without limitation the rights

* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell

* copies of the Software, and to permit persons to whom the Software is

* furnished to do so, subject to the following conditions:

*

* The above copyright notice and this permission notice shall be included in all

* copies or substantial portions of the Software.

*

* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR

* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,

* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE

* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER

* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,

* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE

* SOFTWARE.

*/

// Include following libraries to access IR sensor

#include <IRremote.h>

#include <IRremoteInt.h>

int RECV_PIN = 13; // The digital pin that the signal pin of the sensor is connected to

IRrecv receiver(RECV_PIN); // Create a new receiver object that would decode signals to key codes

decode_results results; // A varuable that would be used by receiver to put the key code into

void setup() {

Serial.begin(9600); // Setup serial port to send key codes to computer

receiver.enableIRIn(); // Enable receiver so that it would start processing infrared signals

}

void loop() {

if(receiver.decode(&results)) { // Decode the button code and put it in "results" variable

Serial.println(results.value, HEX); // Print the code as a hexadecimal value

receiver.resume(); // Continue listening for new signals

}

}

zaerymoghaddam (author)PrakharT12017-10-01

Are you sure you're running this code? This code is using IRremote.h library while your error indicates that there is an error on RobotIRremote library!
You may have installed an invalid library on your Arduino IDE.

DIY Hacks and How Tos (author)2017-07-30

I have used these kinds of sensors in a lot of my projects to make them remote controlled. They work great.

Yeah they're great and easy to use. I mostly use them with a TV remote. It gives a much better result ;)

About This Instructable

1,803views

37favorites

License:

Bio: I'm a software developer interested on robotics and electronics project as a hobby. I really enjoy sharing what I've learned.
More by zaerymoghaddam:Fun With OLED Display and ArduinoUsing Infrared Sensor With Arduino
Add instructable to: