Easier Way Than IrReceiver.decodedIRData.command to Check IR Remote Received Data

Viewed 1798

I'm relatively new to Arduino and I was trying to create a simple sketch that turns an LED light on when I press the up arrow on the remote and turns the LED light off when I press the down arrow. Right now, this is what I have:

#include <IRremote.h>

int RECEIVER_PIN = 12;


void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(LED_BUILTIN, OUTPUT);
  IrReceiver.begin(RECEIVER_PIN);
}

void loop() {
  // put your main code here, to run repeatedly:
  if(IrReceiver.decode()){    
    
    if(IrReceiver.decodedIRData.command == 0x46) {
      digitalWrite(LED_BUILTIN, HIGH);
    } else if(IrReceiver.decodedIRData.command == 0x15) {
      digitalWrite(LED_BUILTIN, LOW);
    }
    
    IrReceiver.resume();
  }

}

Is there a better way to do this or am I on the right track. All feedback is welcomed and appreciated. Thanks!

2 Answers

I'm also new to Arduino and C, but if it was me I'd use "switch" instead of "if..then..else..if..etc" :

    #include <IRremote.h>

    int RECEIVER_PIN = 12;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      pinMode(LED_BUILTIN, OUTPUT);
      IrReceiver.begin(RECEIVER_PIN);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      if(IrReceiver.decode()){    
       switch(IrReceiver.decodedIRData.command){
           case 0x46: Serial.println("UP")                  ; digitalWrite(LED_BUILTIN, HIGH); break;
           case 0x15: Serial.println("DOWN")                ; digitalWrite(LED_BUILTIN, LOW) ; break;
           case 0x0:  Serial.println("Too Fast, Cmd Repeat"); break;
           default:   Serial.println("Ooops, wrong key!");    
        }
        IrReceiver.resume();
      }
    }

Use this code, it works fine

#include <IRremote.h>

int receive_pin=12;
int led=8;

void setup(){
IrReceiver.begin(receive_pin);
pinMode(led,OUTPUT);
Serial.begin(9600);
}

void loop()
{
if(IrReceiver.decode())
{
Serial.println(IrReceiver.decodedIRData.command,HEX);
if(IrReceiver.decodedIRData.command==0x16){
  digitalWrite(led,HIGH);
}
if(IrReceiver.decodedIRData.command==0x19)
{
digitalWrite(led,LOW);
}
delay(1500);
IrReceiver.resume();
}
}
Related