This post is a follow up to part one in the series on GPIO control found at: Tinkernow gpio control part 1. This assumes everything worked properly and your breadboard is still setup with the LED circuit.
We are going to add in a switch to our circuit, wire the switch up to the Beaglebone Black, and use a simple python program to send a signal to turn the LED on and off. This will give us a grasp of some more advanced interactions with our micro controller, as well as using the vi editor. The vi editor is used to create and edit text based files/programs. We will use the vi editor to create a python file, by saving our file extension as .py. More on that below.
First things first, below is a schematic of the switch to be added to the circuit:
Once that is built, install vim with command
now we can begin programming.
**remember we us the Header_Pin layout in programming, so we will not type GPIO_60, we will instead type P9_12.
Run the command:
What this does is create a file in the vi editor called gpiotest the .py tells the system that it is a python file, this is important so don’t leave it off when creating files.
Continuing on, once in the vi editor copy and past this code, be sure to read through it and understand what is happening:
import Adafruit_BBIO.GPIO as GPIO GPIO.setup("P9_24",GPIO.OUT) GPIO.setup("P9_12",GPIO.IN) while True: if GPIO.input("P9_12"): GPIO.output("P9_24",GPIO.HIGH) else: GPIO.output("P9_24",GPIO.LOW)
To exit the editor hit [esc], then type (:wq ) without parenthesis and hit [enter]. When you input the exit command wq, you are saying (w)rite (save program) and (q)uit. If you were using vi to simply look at a file, and didn’t make any edits, you would simply hit :q [enter].
Going line by line here is what this code is doing:
- Imports the adafruit gpio programming library
- Sets up Pin 24 on header 9 as an output.
- Sets up Pin 12 on header 9 as an input.
- 5-9 sets the function that if Pin 12 recieves an input signal, than Pin 24 is set to high (turning on the LED) otherwise it stays low.
Now your code is stored as the python file “gpiotest.py”. To run this code, enter the following command:
This will run the code previously saved to the file gpiotest.py. Now if you press your switch, the LED should turn on.
Check out part 1 and 3 of this 3 part series on gpio control