Friday, September 25, 2015

Python control Raspberry Pi 2 PWR/ACT LED, using RPi.GPIO or system's shell.

Last post show how to "Control Raspberry Pi 2 B on-board ACT LED with Python/RPi.GPIO", this example show how to control both the PWR and ACT LED of Raspberrry Pi 2 B, using Python, with RPi.GPIO and via system's shell by calling os.system().


*Please note that it's for Raspberrry Pi 2 B only*

Refer to Windows IoT document Raspberry Pi 2 Pin Mappings:
Red Power LED's GPIO# is 35.
Green Activity LED's GPIO# is 47.

In my experience, it cannot be perform using sudo, you have to login as root. To login as root, refer to the post "Set password of root".

pyGPIO.py
import sys
import os
import RPi.GPIO as GPIO
import time

print("**********************************************")
print("*** Toggle PWR/ACT LED on Raspberry Pi 2 B ***")
print("***        for Raspberry Pi 2 B only       ***")
print("**********************************************")
print("- System info -")
print(sys.version)
print("GPIO.VERSION: " + GPIO.VERSION)
print("GPIO.RPI_REVISION (deprecated): " + str(GPIO.RPI_REVISION))

print("")
print("GPIO.RPI_INFO:")
print(GPIO.RPI_INFO)

print("")
for keys,values in GPIO.RPI_INFO.items():
 print(keys + " : " + str(values))

print("")
#display trigger for led0 and led1
print("- Original trigger for led 0 -")
os.system("cat /sys/class/leds/led0/trigger")
print("- Original trigger for led 1 -")
os.system("cat /sys/class/leds/led1/trigger")

print("remove the trigger for led0 and led1")
os.system("echo none >/sys/class/leds/led0/trigger")
os.system("echo none >/sys/class/leds/led1/trigger")
os.system("cat /sys/class/leds/led0/trigger")
os.system("cat /sys/class/leds/led1/trigger")
print("")
 
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(35, GPIO.OUT) #Red PWR LED on RPi2B 
GPIO.setup(47, GPIO.OUT) #Green Activity LED on RPi2B

for num in range(1, 5):
    print num
    
    #Control led0 with RPi.GPIO
    GPIO.output(47, False)  #Turn OFF ACT LED for RPi 2 B
    GPIO.output(35, True) #Turn ON PWR LED for RPi 2 B
    print "LED PWR(RED)-ON ACT(GREEN)-OFF"
    time.sleep(2)

    #Control led1 with system's shell
    os.system("echo 1 >/sys/class/leds/led0/brightness")
    os.system("echo 0 >/sys/class/leds/led1/brightness")
    print "LED PWR(RED)-OFF ACT(GREEN)-ON"
    time.sleep(3)

print("")
print("Finished")
#rsume the trigger for led0 and 
#assume it's mmc0 and input
os.system("echo mmc0 >/sys/class/leds/led0/trigger")
os.system("echo input >/sys/class/leds/led1/trigger")

print("- Resummed trigger for led 0 -")
os.system("cat /sys/class/leds/led0/trigger")
print("- Resummed trigger for led 1 -")
os.system("cat /sys/class/leds/led1/trigger")
print("")


No comments: