Saturday, February 21, 2015

Push Button Example

Following the guidelines in our textbook, and adding a few improvements of my own, I have created a script that lets someone interact with an LED using a push button, all driven by software. The script starts a loop that looks for changes in the switch's GPIO pin state, and toggles a state on the LED's GPIO pin accordingly. The script toggles between 4 states in order as the button is pressed; off, on, flickering slowly and flickering more quickly.

A few things I noticed that were unexpected; first, I am really new to wiring diagrams so figuring out how to get the thing wired up on my breadboard took a bit of time.

Second, I was expecting the value set on the GPIO pin by the switch to be binary pressed / not pressed, defaulting to not pressed as False. Instead, the button seems to default to True, so I am assuming the GPIO pin is reading open / closed (defaulting to True for open). This could be a mistake, relating to my inexperience wiring things, but I got it working so I will follow up next class.

Third, software debouncing can be achieved by keeping a boolean variable tracking if state is allowed to be changed or not. Without the debouncing, the state of the switch is read each time the loop cycles, sometimes causing something to happen multiple times because the value was read more than once while the button was down. Only allow state changes to occur if the button is pressed and the tracking variable is set to True. The first time a state change is detected on the switch, set the tracking variable to False before toggling anything. If the button is not being pressed, set the tracking variable to True so the next time is is pressed, state can change. This means only one thing will happen each time you press the button, no matter how long it is held down.

Here is my source code and a wiring diagram of the setup.


And here is the source code.

Wiring diagrams courtesy of Digi-Key's excellent (and free) online schematic editor SchemeIt.

No comments:

Post a Comment