[SOLVED] Control relay with contact button on Openhab problem

Hy,
My name is Mike and I started few days ago to learn openHab and to test things, now I want to control a relay with a reverse button, and i want to create a rule to check if state of relay is ON and then turn OFF and also if it’s OFF to turn ON,
I am new in codding and i don’t know what I’ve done wrong.
I need some help, please.

This is the code from home.items

 Switch buc1_releu "Bec1" (LivingRoom) { gpio="pin:18 activelow:yes initialValue:high force:true" }
    Contact buc1_intrerupator "Intrerupator [%s]" (LivingRoom) { gpio="pin:23 activelow:yes" }
rule "buc1"
when
	Item buc1_intrerupator changed
then
       if (buc1_releu.state == ON){
        sendCommand(OFF)
    }
    else if (buc1_releu.state == OFF){
        sendCommand(ON)
    }
end

Almost!! You are on the right track.
Well done so far, don’t give up

rule "buc1"
when
    Item buc1_intrerupator changed
then
    if (buc1_releu.state == ON) {
        buc1_releu.sendCommand(OFF)
    }
    else if (buc1_releu.state == OFF) {
        buc1_releu.sendCommand(ON)
    }
end
1 Like

Thank youu :slight_smile:, but it does not do anything, there is no error in the log.

@vzorglub, I add the rule, if it’s on he turns off the relay. if it’s off he doesn’t do nothing:)).

i am trying to find the solution from about 4 hours :))

There is a typo in @vzorglub’s code :sunglasses:

Change

to
buc1_releu.sendCommand(ON)

1 Like

It works…you guys are AWESOME!!

Thank you very much!!

1 Like

Just because I can’t help myself, here’s a one liner.

rule "buc1"
when
    Item buc1_intrerupator changed
then
    buc1_releu.sendCommand(if(buc1_releu.state == OFF) ON else OFF)
end

I seem to remember that there was a TOGGLE command at some point. At least I remember it being an option with IFTTT integration. But I don’t know if there is any more or whether that was specific to the IFTTT openHAB channel.

1 Like

i am back with a problem:)).
The if statement doesn’t work properly. if i push the button to close the light it remains closed until i take my hand from the button. like in the video attached

OK, so the button is a momentary button and you want it to work like a toggle.

rule "buc1"
when
    Item buc1_interrupator changed to ON
then
    buc1_releu.sendCommand(if(buc1_releu.state == ON) ON else OFF)
end

With the above, the relay will toggle to it’s opposite state every time the buc1_interrupator changes to ON.