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.pyimport RPi.GPIO as GPIO # Importing the GPIO controller moduleimport 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 cleanlyGPIO.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-iotsudo 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.