====== ColorfulLED ====== **//The Circuit://** {{:hpc0:colourfulled.jpg?nolink|}} **//The Code://** 1 #!/usr/bin/env python3 2 ######################################################################## 3 # Filename : ColorfulLED.py 4 # Description : Random color change ColorfulLED 5 # Author : www.freenove.com 6 # modification: 2019/12/27 7 ######################################################################## 8 import RPi.GPIO as GPIO 9 import time 10 import random 11 12 pins = [11, 12, 13] # define the pins for R:11,G:12,B:13 13 14 #initial setup function 15 def setup(): 16 global pwmRed,pwmGreen,pwmBlue 17 GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering 18 GPIO.setup(pins, GPIO.OUT) # set RGBLED pins to OUTPUT mode 19 GPIO.output(pins, GPIO.HIGH) # make RGBLED pins output HIGH level 20 pwmRed = GPIO.PWM(pins[0], 2000) # set PWM Frequence to 2kHz 21 pwmGreen = GPIO.PWM(pins[1], 2000) # set PWM Frequence to 2kHz 22 pwmBlue = GPIO.PWM(pins[2], 2000) # set PWM Frequence to 2kHz 23 pwmRed.start(0) # set initial Duty Cycle to 0 for Red, Green, Blue 24 pwmGreen.start(0) 25 pwmBlue.start(0) 26 27 #set the colour of the LED 28 def setColor(r_val,g_val,b_val): # change duty cycle for three pins to r_val,g_val,b_val 29 pwmRed.ChangeDutyCycle(r_val) # set Red's value 30 pwmGreen.ChangeDutyCycle(g_val) # set Green's value 31 pwmBlue.ChangeDutyCycle(b_val) # set Blue's value 32 33 #Function that activate and set the LED's colour 34 def loop(): 35 while True : 36 r=random.randint(0,100) #get a random in (0,100) 37 g=random.randint(0,100) 38 b=random.randint(0,100) 39 setColor(r,g,b) #set random as a duty cycle value 40 print ('r=%d, g=%d, b=%d ' %(r ,g, b)) 41 time.sleep(0.3) 42 43 #function to stop the circuit 44 def destroy(): 45 pwmRed.stop() 46 pwmGreen.stop() 47 pwmBlue.stop() 48 GPIO.cleanup() 49 50 if __name__ == '__main__': 51 print ('Program is starting ... ') 52 setup() 53 try: 54 loop() 55 except KeyboardInterrupt: # When program ends 56 destroy() This project consisted of a multi-colour LED three resistors and four jumpers. The resistors connected the different ports of the LED that resemble the red, green, and blue lights of the LED. With the last port connecting to 3.3V part of the board. When the program is ran the LED will change colours, starting from white and going through the main colours in the colour spectrum. As for the code I cleaned it up, primarily shortening the comments that described the call to function that changed the LED's colour. I also added comments to describe the functions in it.