diff --git a/src/examples/pininterrupt/pininterrupt.go b/src/examples/pininterrupt/pininterrupt.go index 0cb29bc854..a283261601 100644 --- a/src/examples/pininterrupt/pininterrupt.go +++ b/src/examples/pininterrupt/pininterrupt.go @@ -3,7 +3,7 @@ package main // This example demonstrates how to use pin change interrupts. // // This is only an example and should not be copied directly in any serious -// circuit, because it lacks an important feature: debouncing. +// circuit, because it only naively implements an important feature: debouncing. // See: https://en.wikipedia.org/wiki/Switch#Contact_bounce import ( @@ -17,6 +17,8 @@ const ( led = machine.LED ) +var lastPress time.Time + func main() { var lightLed volatile.Register8 lightLed.Set(0) @@ -33,6 +35,13 @@ func main() { // Set an interrupt on this pin. err := button.SetInterrupt(buttonPinChange, func(machine.Pin) { + + // Ignore events that are too close to the last registered press (debouncing) + if time.Since(lastPress) < 100*time.Millisecond { + return + } + lastPress = time.Now() + if lightLed.Get() != 0 { lightLed.Set(0) led.Low()