I am trying to make a led turn on, but only when a button is held down on an IR remote. In other words, the led needs to turn off when I take my finger off the button. This remote has one code that goes out for each individual key on it, as well as one code that is sent repeatedly when any button is pressed and held down. I am new to coding, and want to keep this as elegant as possible. Right now, the two main problems are that 1) the if statements don’t run all the way through, the serial print statements show that when it is tested, 2) I think the on off logic is flawed, but I have no idea how to fix it. Please help. Thanks!!!
#include <IRremote.h>
#define ok 3622325019 // code received from button ok
#define held 4294967295 // code when button is held
int RECV_PIN = 9; // the pin where you connect the output pin of TSOP4838
int led1 = 8;
long currentmillis; // the variable to mark the time when the key was received
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
Serial.begin(9600); // you can comment this line
irrecv.enableIRIn(); // Start the receiver
pinMode(led1, OUTPUT);
}
void loop()
{
if (irrecv.decode(&results)) // if IR CODE is received, decode the value
{
Serial.println("Primary IR RECIEVED");
Serial.println(results.value);
if (results.value == ok) //if results.value matches okay
{
Serial.println("OK BUTTON WAS PRESSED");
irrecv.resume(); //look for incoming ir code
Serial.println("WAITING FOR 'Held' IR CODE");
if (irrecv.decode(&results)) // decode secondary incoming ir values
{
Serial.println("Secondary IR RECIEVED");
Serial.println(results.value);
switch (results.value) //if this new value is the 'held code'
{
case held:
Serial.println("BUTTON IS BEING HELD");
digitalWrite(8, HIGH);
currentmillis = millis(); //mark the current time
Serial.println("Starting Time Counter");
if (((millis()- currentmillis)>500) && (results.value == held))
{
Serial.println("Checking Time");
Serial.println("Time Expired");
digitalWrite(8, LOW);
Serial.println("TURNING OFF LED");
}
break;
}
irrecv.resume();
}
}