For more details about Software PWM, please refer to: http://wiringpi.com/reference/software-pwm-library/
Python Code 5.1.1 ColorfulLED
First observe the project result, and then analyze the code.
1. Use cd command to enter 05.1.1_ColorfulLED directory of Python code.
cd ~/Freenove_Ultimate_Starter_Kit_for_Raspberry_Pi/Code/Python_Code/05.1.1_ColorfulLED
2. Use python command to execute python code “ColorfulLED.py”.
python ColorfulLED.py
After the program is executed, you will see that the RGBLED shows light of different color randomly.
The following is the program code:
im port RPi. GPIO as GPIO
im port time
im port random
pins = {'pin_R':11, 'pin_G':12, 'pin_B':13} # pins is a dict
def setup():
g lobal p_R,p_G,p_B
p rint ('Program is starting ... ')
GPIO. setmode(GPIO.BOARD) # Numbers GPIOs by physical location
for i in pins:
GPIO.setup(pins[i], GPIO. OUT) # Set pins' mode is output
GPIO.output(pins[i], GPIO. HIGH) # Set pins to high(+3.3V) to off led
p_R = GPIO.PWM(pins['pin_R'], 2000) # set Frequece to 2KHz
p_G = GPIO.PWM(pins['pin_G'], 2000)
p_B = GPIO.PWM(pins['pin_B'], 2000)
p_R. start(0) # Initial duty Cycle = 0
p_G. start(0)
p_B. start(0)
def setColor(r_val,g_val,b_val):
p_R. ChangeDutyCycle(r_val) # Change duty cycle
p_G. ChangeDutyCycle(g_val)
p_B. ChangeDutyCycle(b_val)
def loop():