This is part 2 in my Sunfounder Superkit series.

Blinking an LED was too easy! Let's make this piece interactive. Buttons are exactly the magic I'm looking for. Push it, and do something. ANYTHING! Let's keep it simple and build off of our first simple LED hookup.

Wiring a button to an LED on a Raspberry Pi B+

With that in place, and a little Ruby script, we can loop in the button to join the LED blinking fun.

The Great Ruby Takeaways

Ok, so maybe the circuit is not that exciting, but this is just the start! With this we've gained some exposure to both listening in on and controlling the state of GPIO pins. Writing this script also introduces us to some great aspects of working with Ruby programs from a lower level.

IO#flush and IO#sync

Firstly, STDOUT.flush . This will clear any buffered data to standard out allowing future calls to puts to replace what was there. Little did I know there is a flag you can set on an IO instance to immediately flush the output after every call with: STDOUT.sync = true .

Kernel#at_exit

Ruby's Kernel comes with some great stuff for working with the command line. The fine folks over at HoneyBadger have a great writeup on different ways to exit a Ruby program, and some best practices. In this specific case, we can use the special at_exit callback to perform some code to reset the state of our GPIO pins (so we make sure not to set any fires).

Interrupt and SignalException

Lastly, because we want to ensure that our circuit resets itself whenever the program stops running, we need a way to catch both user-initiated interrupts (a.k.a Interrupt caused by a ctrl+c) and system-initiated interrupts (a.k.a. SignalException ). While it may be more beneficial to trap unix signals, I went with the quick and dirty.

Hopefully you learned something today. I know I did! Tune in next time when I get serious with the breadboard and jam as many LEDs in it as I can (or have patience for).