In this lesson we are ready to bring together a lot of what we learned in earlier lessons. We will create dimable LEDs which will respond to two buttons. If one is pressed the LED will gradually grow dimmer. If the other is pressed, the LED will gradually grow brighter. This will require us to use our skills in using GPIO inputs, pullup resistors, GPIO outputs, and PWM.
For convenience we will use the same circuit we used in LESSON 30, shown below. Also, if you want to follow along with these lessons, you can buy the gear you need HERE.
The objective of this circuit is that we want the LEDs to grow brighter each time the right button is pushed, and we want them to grow dimmer each time to left button is pushed.
The video above steps through and explains this code.
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 | from time import sleep # Library will let us put in delays import RPi.GPIO as GPIO # Import the RPi Library for GPIO pin control GPIO.setmode(GPIO.BOARD)# We want to use the physical pin number scheme button1=16 # Give intuitive names to our pins button2=12 LED1=22 LED2=18 GPIO.setup(button1,GPIO.IN,pull_up_down=GPIO.PUD_UP) # Button 1 is an input, and activate pullup resisrot GPIO.setup(button2,GPIO.IN,pull_up_down=GPIO.PUD_UP) # Button 2 is an input, and activate pullup resistor GPIO.setup(LED1,GPIO.OUT) # LED1 will be an output pin GPIO.setup(LED2,GPIO.OUT) # LED2 will be an output pin pwm1=GPIO.PWM(LED1,1000) # We need to activate PWM on LED1 so we can dim, use 1000 Hz pwm2=GPIO.PWM(LED2,1000) # We need to activate PWM on LED2 so we can dim, use 1000 Hz pwm1.start(0) # Start PWM at 0% duty cycle (off) pwm2.start(0) # Start PWM at 0% duty cycle (off) bright=1 # Set initial brightness to 1% while(1): # Loop Forever if GPIO.input(button1)==0: #If left button is pressed print "Button 1 was Pressed" # Notify User bright=bright/2. # Set brightness to half pwm1.ChangeDutyCycle(bright) # Apply new brightness pwm2.ChangeDutyCycle(bright) # Apply new brightness sleep(.25) # Briefly Pause print "New Brightness is: ",bright # Notify User of Brightness if GPIO.input(button2)==0: # If button 2 is pressed print "Button 2 was Pressed" # Notify User bright=bright*2 # Double Brightness if bright>100: # Keep Brightness at or below 100% bright=100 print "You are at Full Bright" pwm1.ChangeDutyCycle(bright) # Apply new brightness pwm2.ChangeDutyCycle(bright) # Apply new brightness sleep(.25) # Pause print "New Brightness is: ",bright #Notify User of Brightness |