Handling a button

Im having a little difficulty with a button i need for my project.
Its very simple, as described here
it has no push-no push, its just clickable.
i made a circuit from 3v3 to the button, and from the button to pin5.
I also, just for understanding, added two leds, at pins 8 & 9.
local times = time(); local state = 0; function ledControl() { times = time() - times; if (times > 1000) { if (state == 0) { state = 1; } else { state = 0; } if (state == 1) { hardware.pin8.write(1); hardware.pin9.write(0); } else { hardware.pin8.write(0); hardware.pin9.write(1); } times = time(); server.log("ledControl"); } } hardware.pin5.configure(DIGITAL_IN_PULLDOWN, ledControl);

at the moment, what that happens is that sometimes pressing causes color to go red -> green,
which is ok, beacuse its what i wanted…1 callback.
but sometimes it reads 1 physical click as 2, generating two callbacks and therefore led is red -> green -> red
Is there any mechanism i can have only 1 callback, somehow to ignore two clicks very close one to the other?
Or should i just create another variable for seeing last time it clicked, and if its very small time difference, to ignore it in the second callback?

Edit: I tried adding time but it still sometimes reads a click as 2 callbacks and sometimes as only 1.
can anyone advice?

With a perfect switch, you’ll get 2 callbacks - one for the press and one for the release. You may get many more, due to switch “bounce”.

I can see you have a debounce in there (looking for a minimum difference in time) but you should also add " && hardware.pin5.read() == 1 " to your if (times>1000) line, so that you only run that code on a button press.

thanks hugo, sadly i missed to add this part.
i set it back to times > 0.5, so its reasonable. if i clicked slower than 0.5s so thats “human”,
works perfectly.
I hope i will get the rest of my project parts, to add a nice thread to “Got imps?” soon :slight_smile: