From d245fa7b070d6290ee5acbda70d1cc107348c29e Mon Sep 17 00:00:00 2001 From: Yurii Soldak Date: Fri, 5 Nov 2021 23:16:25 +0100 Subject: [PATCH] example: naive debouncing for pininterrupt example --- builder/sizes_test.go | 2 +- src/examples/pininterrupt/pininterrupt.go | 11 ++++++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/builder/sizes_test.go b/builder/sizes_test.go index a1be28f274..801a1184e9 100644 --- a/builder/sizes_test.go +++ b/builder/sizes_test.go @@ -44,7 +44,7 @@ func TestBinarySize(t *testing.T) { // microcontrollers {"hifive1b", "examples/echo", 4600, 280, 0, 2268}, {"microbit", "examples/serial", 2908, 388, 8, 2272}, - {"wioterminal", "examples/pininterrupt", 6140, 1484, 116, 6824}, + {"wioterminal", "examples/pininterrupt", 7286, 1486, 116, 6912}, // TODO: also check wasm. Right now this is difficult, because // wasm binaries are run through wasm-opt and therefore the diff --git a/src/examples/pininterrupt/pininterrupt.go b/src/examples/pininterrupt/pininterrupt.go index e13ba5eb3a..df3a0a9056 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 ( @@ -15,6 +15,8 @@ const ( led = machine.LED ) +var lastPress time.Time + func main() { // Configure the LED, defaulting to on (usually setting the pin to low will @@ -29,6 +31,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() + led.Set(!led.Get()) }) if err != nil {