28 May 2015

Toggle button

I am new to Arduino and C++ and as usual for first-timers, the first project has to do something with some LED-s and buttons.
Nothing complicated, but looking at examples I realized quite soon that there is lot of coding that has to be done to have proper toggle button functionality with debounce handling. Too much  for such a simple thing as push button. And if there happens to be multiple buttons, then it gets even worse. So, there has to be some library that handles all this, there probably is, but I decided that I need to practice some C++ and create my own library. So, couple of days tinkering and here is my first library, named PBtnToggle found in GitHub.
This library handles debouncing, has button press event, release event and long press event. And does not use delay(). User can decide what happens after long press - will it trigger release event after button release or trigger after next button press and release. I am quite happy what I created. There is some changes I would like to do at some point, but I decided that current version is ready for public.

Here's a demo video:


So, how much coding have to be done to use this library?
Lets take Switch example code from Arduino website. Let's change this to use PBtnToggle.
  1. Include PBtnToggle library:
  2. Init PBtnToggle object, specify pin where button is wired and pin state when button is pressed down. This will also set pin mode to INPUT:
  3. In setup(), register function that will be called when button is pressed down:
  4. Create function that will be called by library, registered in setup(). This function will contain anything that has to be done in button press:
  5. Call check() function, without this PBtnToggle will not work:
Atleast for me, this code looks a lot nicer. This is end result that does same thing that example code from Arduino webpage. Compiler log for original code:
Compiler log for PBtnToggle example code:
So library takes about 1KB extra flash and memory footprint is about same. But your sketch will be probably smaller if you have multiple buttons.

Please, let me know if this library is useful for you and if you have some ideas that could improve this library, then please let me know here in comments or in GitHub for more technical ideas/fixes.
Also, if you know any other libraries that do something similar, then let me know about it. I would like to compare them.