I am using this sketch below to switch a relay on when I press button 1 on a RF keyfob and staying on until I press button 1 again.
The below sketch does exactly that but once I turn it off from the on state, it will not switch back on again. It's almost as if the sketch is reading low and trying to switch it to low or something, I don't really have any idea what is going on. My RX is still receiving the code that switches the relay, even once the relay won't switch again.
If someone could please steer me in the right direction in terms of fixing this sketch to toggle on and off as many times as I wish, that would be great.
Thanks in advance!
#include <RCSwitch.h>
#define RELAY1 5
int val = 0;
int old_val = 0;
int state = 1;
int RELAY = 5;
RCSwitch mySwitch = RCSwitch();
void setup() {
Serial.begin(9600);
pinMode(RELAY1, OUTPUT);
mySwitch.enableReceive(0);
}
void loop() {
if (mySwitch.available()) {
unsigned long value = mySwitch.getReceivedValue();
if (value == 5592323UL) {
val = digitalRead(RELAY1);
if ((val == HIGH) && (old_val == LOW)) {
state = 1 - state;
}
old_val = val;
if (state == 1) {
digitalWrite(RELAY1, HIGH);
} else {
digitalWrite(RELAY1, LOW);
}
mySwitch.resetAvailable();
}
}
}
Why do you need to read this? You don't seem to have any problem remembering the pin number. Remember the state, too. (Though in a variable, not a #define).
Put each { on a new line. Use Tools + Auto Format to properly indent your code. You have this:
if (mySwitch.available())
{
unsigned long value = mySwitch.getReceivedValue();
if (value == 5592323UL)
{
mySwitch.resetAvailable();
}
}
Please explain why you reset only if you get that specific value.
If you KEPT your code properly indented, you'd see that you were doing stupid stuff like that.
Without studying the code more, which I shouldn't have too, since you should be able to remember what you set the pin too (since you seem to be able to remember what you read from the pin last time), there are probably other stupid things you are doing, storing stuff inappropriately.