One of the main features of the raspberry pi is the GPIO port, a 21 pins connector where you can attach external hardware and have fun.
gem install wiringpi
Today we’re going to use ruby to monitor a push button that, when pressed, will activate a LED diode.
On the GPIO port we can use pins 0 to 7 either for input or output (see then complete reference for GPIO pins here). We’re going to use pin 1 for the button and pin 4 for the LED.
So, the connections from the GPIO port to the breadboard with electric parts are as follows:
Now that the hardware is ready, let’s write some code:
require 'wiringpi' # initialize the GPIO port: gpio = WiringPi::GPIO.new # name the pins, for easier reference: button = 1 led = 4 # initialize the pin functions: gpio.mode button, INPUT gpio.mode led, OUTPUT # turn off the led, just in case: gpio.write led, 0 # loop on all the pins, when the button pin has # 0 value (button is pressed) the led will turn # on. loop do state = gpio.readAll if state[button] == 0 gpio.write led, 1 end sleep 0.3 end