Controlling LED output

First IoT Program

Let’s write our first program to toggle a LED connected with GPIO pin on our virtual target. We are going to create a simple python program named hello-led.py with the following contents.

hello-led.py
import RPi.GPIO as GPIO # Importing the GPIO controller module
import time
​
print("Hello LED")
ledPin = 9
​
print("Setting Broadcom Mode")
# Pin Setup:
GPIO.setmode(GPIO.BCM) # Broadcom pin-numbering scheme
​
#GPIO.setmode(GPIO.BOARD) ---> Board numbering scheme
​
print("Setting LED as an output")
GPIO.setup(ledPin, GPIO.OUT)
​
print("Here we go! Press CTRL+C to exit")
try:
while 1:
print ("OFF");
GPIO.output(ledPin, GPIO.LOW)
time.sleep(1.00)
print ("ON");
GPIO.output(ledPin, GPIO.HIGH)
time.sleep(1)
except KeyboardInterrupt: # If CTRL+C is pressed, exit cleanly
GPIO.cleanup() # cleanup all GPIO

We have already downloaded the code at the folder hello-iot. To run this program on the target, open a command prompt from clicking the top left icon

and type following

cd hello-iot
sudo python hello-led.py

The program will run in a loop and toggle the LED on PIN number 9. We switch the Webview tab to see the effect in action.

Press Ctrl+C to stop the program.

Congratulations! We now know how to control the GPIO pins.