Event handler on input state change

I’ve written a simple bit of code to take a button input to the imp. It sends the button value to the server, and outputs a count of the number if times it has been pressed.

I trigger the function whenChanged() when pin 8 sees a change of state

The variable ‘buttonCount’ should increase by 1 every time the button is pressed, but it’s going up by 2.

Any ideas?

`//Blue Button

local buttonState;
local buttonCount = 0;
local output = OutputPort(“Result”, “number”);

function whenChanged()
{
imp.sleep(0.05);
buttonState = hardware.pin8.read();
buttonState = buttonState?0:1;
if (buttonState){
buttonCount++;
}
server.show(buttonState);
output.set(buttonCount);
}

//define input pin
hardware.pin8.configure(DIGITAL_IN_PULLUP, whenChanged);

// Register with the server
imp.configure(“Blue Button”, [], [output]);

// End of code.`

Looks like you are counting when it’s pushed AND when it’s released.

That function whenChanged() will run on any change of state, but I added the lines

if (buttonState){ buttonCount++; }

to only increment the count when the button is currently pressed (1)

To me it looks like you need more debounce. I think something like this would work

`//Button with some debounce time

local buttonCount = 0;
local pending = false;
local output = OutputPort(“Result”, “number”);

function buttonCheck()
{
if (hardware.pin2.read())
{
buttonCount++;
server.show(buttonCount);
output.set(buttonCount);
}

pending = false;

}

function whenChanged()
{
if (!pending)
{
pending = true;
imp.wakeup(0.100, buttonCheck);
}
}

//define input pin
hardware.pin2.configure(DIGITAL_IN_PULLUP, whenChanged);

// Register with the server
imp.configure(“Blue Button”, [], [output]);

// End of code.`