Let's write LED blinking code in Python. Connect one external LED in series with a resistor to pin P8_10 like we did in Chapter 3, Blinking External LEDs. Type the following program in Cloud9, save it as blink_external_LED.py
and run. You should be able to see an LED blinking each second:
The code for blink_external_LED.py
is as follows:
#!/usr/bin/python from time import sleep ##Needed to call sleep() import Adafruit_BBIO.GPIO as GPIO led = "P8_10" GPIO.setup(led,GPIO.OUT) while True: GPIO.output(led,GPIO.HIGH) sleep(1) GPIO.output(led,GPIO.LOW) sleep(1)
Now, let's go through the above-mentioned code snippet one step at a time. If you observed, there is no semicolon (;
) at the end of lines in Python. There are no curly braces to indicate statements inside a while
loop. Statements inside a loop are indented. Here is a line-by-line explanation of the code.
/usr/bin/python
. Now, you can change the permission of this file to executable and run directly in the shell. Shell will read the first line and execute it through the Python interpreter:sudo chmod +x /var/lib/cloud9/blink_external_LED.py /var/lib/cloud9/blink_external_LED.py
sleep()
function from the time
library. Comments in Python start with the symbol "#
" similar to the shell program. Long multiline comments can be enclosed in triple apostrophes. For example '''This is comment'''
Adafruit_BBIO
library and named it GPIO. This namespace has all the variables and functions related to GPIO. For detailed information about GPIO theory and GPIO pins on BeagleBone, please refer to Chapter 3, Blinking External LEDs.led
and assigned it the value P8_10,
GPIO
pin P8_10
is connected to our external LED. Now, we can access an actual LED via our led
variable.GPIO.setup()
. This function is similar to the pinMode()
function from BoneScript. The GPIO.setup(
) function sets the direction of the specified GPIO pin as input
or output
. As the LED is a component of "output" type, we set the direction as "output" for the pin. Now, we can write HIGH or LOW on the LED.while
loop starts here. The condition for this loop is – True
. "while
True
:" is equivalent to while(1)
in C. This loop will run for ever. The number of indentations specifies which loop we are in. For statements inside a single loop, you use a single "tab" indentation. For statements inside a loop that is inside a single loop, you use a double "tab" indentation and so on. If you use the indentation incorrectly, the statement will be wrongly interpreted as part of another loop or you will get an indentation error.GPIO.output()
and sleep()
. The function GPIO.output()
sets the LED pin HIGH
, which glows the actual LED. Then the program sleeps for a second. After a second, it sets the LED pin LOW
, which will turn off the actual LED. Then the program again sleeps for a second. This sequence runs for ever and we see the LED blinking for a second.18.222.32.67