mnishiguchi

mnishiguchi

Nerves Core Team

Debouncing `:circuits_gpio` messages on button push

I detect the button push by using Circuits.GPIO.set_interrupts(gpio_ref, :rising); however it is too sensitive that I want to debounce it. I am thinking about setting a condition using the second data item in the message tuple {:circuits_gpio, 17, 1233456, 1} for controlling the sensitivity. Is it good? Is there a better way?

My target is Rpi4. My button is a 6mm mini button.

defmodule LedBlinker.Button do
  use GenServer, restart: :temporary

  @debounce_time 200_000_000

  def start_link({gpio_pin, on_push_fn}) when is_number(gpio_pin) and is_function(on_push_fn) do
    GenServer.start_link(__MODULE__, {gpio_pin, on_push_fn})
  end

  def init({gpio_pin, on_push_fn}) do
    # Get a ref to the GPIO pin.
    {:ok, gpio_ref} = Circuits.GPIO.open(gpio_pin, :input)

    # Get messages every time the button is pushed.
    Circuits.GPIO.set_interrupts(gpio_ref, :rising)

    {
      :ok,
      %{
        gpio_pin: gpio_pin,
        gpio_ref: gpio_ref,
        last_pushed_at: 0,
        on_push_fn: on_push_fn
      }
    }
  end

  def handle_info({:circuits_gpio, _, at, 1} = message, state) do
    %{last_pushed_at: last_pushed_at, on_push_fn: on_push_fn} = state

    # Debounce the message.
    if @debounce_time < at - last_pushed_at do
      on_push_fn.(message)
    end

    {:noreply, %{state | last_pushed_at: at}}
  end
end

Most Liked

dominicletz

dominicletz

Creator of Elixir Desktop

Cool, I think you’ve found the best solution. Just in case though I wanted to provider another option. I’ve had a couple of cases where I needed debounce behaviour and implement a module:

if you add this module to your dependencies:

def deps do
   [{:debouncer, "~> 0.1.3"}]
end

you can just do:

  def handle_info({:circuits_gpio, _, at, 1}, %{on_push_fn: on_push_fn} = state) do
    Debouncer.immediate(:circuits_gpio, fn -> on_push_fn.(at) end, 5_000)
    {:noreply, state}
  end 

And it will ensure that the event identified by the first argument (:circuits_gpio) is not triggered more often than every 5_000 millisecond.

There is actually a range of different debounce behaviors I needed in some of my projects so the module implements four different functions. All of them take 3 argument: (event_key, function, timeout)

  • apply() - executes an event after TIMEOUT and so creates a regular interval from frequent events
  • immediate() - is the same as apply() but triggers also immediate on the first event
  • immediate2() - executes the first event as well immediately but mutes all further events until after TIMEOUT
  • delay() - every event delays the trigger by TIMEOUT, will issue an event only once there has been no event for TIMEOUT milliseconds

Or here in a text graph:

  EVENT        X1---X2------X3-------X4----------
  TIMEOUT      ----------|----------|----------|-
  ===============================================
  apply()      ----------X2---------X3---------X4
  immediate()  X1--------X2---------X3---------X4
  immediate2() X1-----------X3-------------------
  delay()      --------------------------------X4

Hope this helps some readers.

mnishiguchi

mnishiguchi

Nerves Core Team

Wow, nice! Thanks. I will definitely keep that in my toolbox.

ondrej-tucek

ondrej-tucek

I’d use send_after & cancel_timer or sleep functions instead of if statement. For example: Process.send_after(self(), {:debounce, on_push_fn, msg}, @debounce_time) + handle_info for :debounce.

Where Next?

Popular in Questions Top

baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New

Other popular topics Top

JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 53690 245
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43622 214
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New
marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New

We're in Beta

About us Mission Statement