Help changing this IR sketch to RF

Hi all,

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! :smiley:

#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();
    }
  }
}