Simple Start to Using the GPIO PinsThe Raspberry Pi is a small single board computer aimed at the hobby and education markets. It comes in two flavours, model A and model B. Model A has only one USB port and no Ethernet jack, it retails at $25. Model B is the more popular board includes 2 USB ports and an Ethernet connection. It retails at $35. Both include the GPIO pins so this post will apply to them both, although you will need to do additional work to get the required libraries installed on the model A since you can't download them from the Internet.
Getting StartedI will be using Arch as my distribution of choice and will be programming in Python 3. If you are using Raspbian most of this will still apply, just some translation of the install commands will have to happen. After installing Arch and booting up your Pi you will need to install some software. To do that we will be using pacman.
Once that completes you can then write your test program. Create a new file named button.py and type in the program below.pacman -S gcc python python-pip pip install RPi.GPIO
Let's walk through exactly what this program is doing. We import the needed libraries at the top, then we set the GPIO mode. The mode allows use to choose whether to use the Raspberry Pi GPIO number scheme (GPIO.BOARD) or the BCM chip GPIO numbering scheme (GPIO.BCM). I have chosen to use the Raspberry Pi's scheme as it will hopefully be more future compatible. Traditionally when working with microprocessors the microchips numbering scheme is used. In this case we are using GPIO 17 so if we wanted to go that route we could just change the mode to be BCM and line 12 to look like:#!/usr/bin/python import time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) GPIO.setup(11, GPIO.IN) count = 0 while True: if not GPIO.input(11): count += 1 print ("button pushed", count) time.sleep(.2)
The rest of the program is simple. We set our pin to input mode and initialize a counter. It then goes to an infinite loop checking if the button is pushed. If it is it increments a counter and displays that count then it sleeps for a short time and does it again. The sleep is there to provide for some rudimentary button de-bounce and also to give you a chance to get your finger off the button before the counter is incremented another time.if not GPIO.input(17):
Circuit LayoutThe circuit we are going to build is simple when the button is pushed the LED will light and if the button.py program is running you should see the counter increment. When you get tired of this just hit control C to end the program.
- 10K Resistor
- 1K Resistor
- SPST NO momentary switch
- LED of some kind
Remember to use the 3.3v output of the GPIO as the Pi is not 5v tolerant. To test your circuit turn on the Pi and push the button, if everything goes right you should see the LED light up.
Post a Comment