In this video lesson we show how you can use pushbuttons and PWM (Pulse Width Modulation) to mix colors and create any color you want in an RGB LED. We are using the most excellent Sunfounder Ultimate Raspberry Pi kit, which you can snag HERE.
You will need to start by connecting up the following circuit. You will find all the components you need in the Sunfounder kit.
You can click on the circuit diagram for a bigger view. In the video above, we explain in detail the coding but for your convenience, we include the finished code below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | import RPi.GPIO as GPIO from time import sleep dt = .1 rPin = 37 gPin = 35 bPin = 33 rBut = 11 gBut = 13 bBut = 15 rButState = 1 rButStateOld = 1 gButState = 1 gButStateOld = 1 bButState = 1 bButStateOld = 1 GPIO.setmode(GPIO.BOARD) GPIO.setup(rPin, GPIO.OUT) GPIO.setup(gPin, GPIO.OUT) GPIO.setup(bPin, GPIO.OUT) GPIO.setup(rBut, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(gBut, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(bBut, GPIO.IN, pull_up_down=GPIO.PUD_UP) myPWMr = GPIO.PWM(rPin, 100) myPWMg = GPIO.PWM(gPin, 100) myPWMb = GPIO.PWM(bPin, 100) DCr = .99 DCg = .99 DCb = .99 myPWMr.start(int(DCr)) myPWMg.start(int(DCg)) myPWMb.start(int(DCb)) try: while True: rButState = GPIO.input(rBut) gButState = GPIO.input(gBut) bButState = GPIO.input(bBut) print('Button State', rButState, gButState, bButState) if rButState == 1 and rButStateOld == 0: DCr = DCr*1.58 print('Red Channel Registered') if DCr > 99: DCr = .99 myPWMr.ChangeDutyCycle(int(DCr)) if gButState == 1 and gButStateOld == 0: DCg = DCg*1.58 print('Green Channel Registered') if DCg > 99: DCg = .99 myPWMg.ChangeDutyCycle(int(DCg)) if bButState == 1 and bButStateOld == 0: DCb = DCb*1.58 if DCb > 99: DCb = .99 myPWMb.ChangeDutyCycle(int(DCb)) rButStateOld = rButState gButStateOld = gButState bButStateOld = bButState print(DCr, DCg, DCb) sleep(dt) except KeyboardInterrupt: GPIO.cleanup() print() print('GPIO Good to Go') |