Button turning on and off a relay

I have the code below that i am trying to use to turn on/off a relay. If i turn the relay on via a function clicking the button will turn it off. so the else part is working. its the if part that doesn’t seem to work to me.

void b1101PopCallback(void *ptr) {
    stsacrelay = digitalRead(acrelay);
    //else return = -1;
    Particle.publish("Debug", "AC Relay On", 300, PRIVATE);
    //digitalWrite(acrelay, HIGH);

Maybe there’s some preprocessor that handles it, but those conditionals don’t look normal to me. I’d use if (stsacrelay == 0). In this case if you’re not using the value afterrwards you might be able to get away with digitalWrite(acrelay, !digitalRead(acrelay)); (If you are using the value afterwards then I’d set it when you write to the pin).

I am trying to read the pin and see the state then change the state of the pin to the opposite value. Basically using a button to turn on the relay if it is off and turn off the relay if it is on.

Oh, I see an issue you have. There’s a ; at the end of your else. That will end the else, so even if the first digitalWrite sets it high you’re still always going to be setting it low right afterwards (fast enough that it won’t flip).

In general with if statements it’s safer if you try to use {}. C doesn’t care about spacing so this will save you headaches, especially when you come along later and add some debugging. For example:

    if (stsacrelay == 0) {
        digitalWrite(acrelay, HIGH);
    } else {
        digitalWrite(acrelay, LOW);

That’s it exactly, Works like I wanted it to thank you so much. I thought I had tried that configuration. But I guess not

1 Like