Tuesday, March 14, 2017

Teensy 3.6 Basics: Using the Bounce2 Library

The Bounce2 library by Thomas Fredericks allows an Arduino-compatible microcontroller to easily read mechanical buttons and switches while avoiding the issue of bouncing. A digital input used to read the state of the switch or button, representing this as either 0 (LOW) or 1 (HIGH) - physically and electrically connected to ground or positive voltage (usually 3.3V or 5V).

Bouncing occurs when a switch or button is used, and the mechanical contact will make and then break contact a number of times before stabilising as the new state. This introduces unwanted errors and fluctuations when reading a digital input pin using a microcontroller.

Hardware Setup
As an example, a pushbutton is connected between ground and digital pin 32 on a Teensy 3.6 board, as shown below.  The Bounce2 library may have been included in the installation of the Teensyduino library.

Software Setup
To use this button with the Bounce2 library:

  • Import the Bounce2 library into the sketch
  • Create a Bounce2 object associated with a name
  • In the setup() function, set the digital pin as an input
  • In the setup() function, attach the digital pin to the Bounce2 object 
  • In the setup() function, set an interval time in milliseconds to debounce the input - 5 - 50 milliseconds is recommended, the shorter the better (as long as a clear and stable signal can be read)
  • In the loop() function, update the Bounce2 object regularly 
  • In the loop() function or elsewhere, read the state of the button or changes in the state of the button

Example 1 - Reading the State of a Button
In this example, the aim is to read the state of the button, and have the onboard LED of the Teensy 3.6 light up in continuous correlation with the state of the button.

Download here: http://milkcrate.com.au/_other/downloads/arduino/teensy_3_6_basics/Using_the_Bounce2_Library_Example_1/

Example 2 - Reading the Change in State of a Button
In this example, the aim is to read the state of the button, and have the onboard LED of the Teensy 3.6 either turn on or turn off only when the state of the button is changed (i.e either went from being pressed to depressed or from depressed to pressed).

Download here: http://milkcrate.com.au/_other/downloads/arduino/teensy_3_6_basics/Using_the_Bounce2_Library_Example_2/

The Bounce2 library can be used to debounce mechanical switches and buttons connected to digital pins, as well as detecting changes in state of a button.

Note the important difference between reading a state (i.e. is the button down or up) and a change in state (i.e. the button goes from being down to being up or from being up to being down).