How to Program an IR Sensor

Ir Sensor uses input from a controller to return a response. TVs, DVD players, etc uses IR sensors to receive input from a controller or TV remote to operate.

Code

#include <IRremote.h>

IRrecv receiver(1);
decode_results output;

You’re going to need two instantiations, a receiver and a result output. The “IRrecv” is going to instantiate the digital pin for the IR sensor and the “decode_results” is where the input code is going to be stored.

void setup() {
  
  Serial.begin(9600);
  receiver.enableIRIn();

}

You’re going to need this line of code in order for the sensor to start processing incoming signals.

void loop() {

if(receiver.decode(&output))
{
  Serial.println(output.value,HEX);
  receiver.resume();
}
}

How the conditional work is that if the sensor receives an input/signal, it’s going to decode the button address and put it in the results variable. “Serial.println(output.value, HEX)” prints the button address in Hexadecimal.

if (receiver.decode(&results)) {            
 if (results.value == 0xFF6897) {  //   #1 on remote
       Serial.println("number pad 1 is pressed")
    }
 if (results.value == 0xFF9867) {  
       Serial.println("number pad 2 is pressed")        //  #2 on remote
    }
 if (results.value == 0xFFB04F) {   
       Serial.println("number pad 3 is pressed")       //   #3 on remote
    }

The last explanation printed out the button addresses. To make the buttons do an action, get the button address from the previous example and create a conditional for when you press any of the buttons.

Final Code

#include <IRremote.h>

IRrecv receiver(1);
decode_results output; //input from remote

void setup() {
  Serial.begin(9600);
  receiver.enableIRIn();//enable IR sensor

}

void loop() {

if (receiver.decode(&results)) {            
 if (results.value == 0xFF6897) {  //   #1 on remote
       Serial.println("number pad 1 is pressed")
    }
 if (results.value == 0xFF9867) {  
       Serial.println("number pad 2 is pressed") //  #2 on remote
    }
 if (results.value == 0xFFB04F) {   
       Serial.println("number pad 3 is pressed") //   #3 on remote
    }
}

Leave a comment

Your email address will not be published. Required fields are marked *