Latching on or off

I understand the programming side of things, I'm just having 'writers-block' if you will. I was hoping you guys could help out :slight_smile:

I have a Processing script sending values via Xbee to my Arduino. The data itself isn't important.

The code goes a little like this (written in faux-code as I don't have my script here):

void loop () {
	if (a.pressed()) {
		lights = lights ? 1 : 0;
	} 
	sendLightState(lights);
}

The a.pressed() command is asking whether I've pressed a button on the PC, and if so, change the status of the lights. I want to be able to press the button and the lights turn on and stay on, then press again for them to turn off.

However, if I hold down the button, the a.pressed() is true on every loop and the lights flicker, and depending when I remove my finger from the button, they either stay on or stay off. This is the behavior I want to remove; if you hold down the button, it should stay with the state the lights were changed to (if the lights are off at the time, holding the button should turn them on).

Can anyone help?

Your code says to reverse the state of the light while the button is pressed every time it goes around the loop. Hence the flicker. When the button is released, stop reversing the state, so the light stays in its last state.

You need a boolean that is true when the switch is off. When the button is pressed and the boolean is true, reverse the state of the lights and set the boolean false. That way you only get one reversal each time the switch is pressed.

So:

boolean lightState = true;
int lights = 0;

void loop () {
	if (a.pressed()) {
                if (lightState) { // If this is true
                    lights = lights ? 1 : 0;
                    lightState = false;
                }
	} else {
                 lightState = true;
        }
	sendLightState(lights);
}

Again, haven't tested this but it seems to (in my head) work. Thanks for the help PeteC