In LESSON 10 we showed you how to create a dimable LED using the analog input from a potentiometer. In this lesson we will create a dimable LED using digital buttons. We will say we want a press of the top button to make the LED brighter, and a press of the bottom button to make the LED dimmer. In order to get going, you will need to build this circuit. If you do not already have a Beaglebone Black, you can get one HERE.
In this circuit make note that we are using two 1000 ohm resistors as pull down resistors on the push buttons. It is important that these resistors be at least 1000 Ohm each. Next, notice the current limiting resistor on the LED is 330 Ohm. We establish a ground rail on the breadboard from pin P9_2 on the Beaglebone Black. We establish our 3.3 Volt rail on the breadboard from pin P9_4 on the Beaglebone. We will use P9_14 as the PWM pin to control the LED, and we will use pins P9_23 and P9_27 as our digital input pins.
We will want a press of the top button to increase brightness and a pres of the bottom button to decrease brightness. As we discussed in Lesson 10, we want to insrease and decrease PWM signal exponentially, as this will allow the eye to perceive a smooth and linear increase in brightness.
If we want the LED to go from full off to full brightness in 10 steps, we need an equation to relate Duty Cycle to BP. BP will be a variable that will keep track of where we are. If we press the up button we increment BP by 1. If we press the down button, we decrements BP by 1. We want to start with BP=0, and the LED full off. This would be the point:
(BP,DutyCycle) = (0,0)
When the button has been pressed 10 times, we want a DutyCycle of 100%. This would be the point:
(BP,DutyCycle) = (10,100)
We now need to fit an exponential curve through these two points.
DutyCycle = C^(BP) -B
We need to figure out what the constants C and B need to be. Note DutyCycle and BP are our variables . . . they are like X and Y. We can plug our first point in and solve for B.
0 = C^0 – B
Anything raised to 0 equals 1, so the equation becomes
0 = 1 – B
Now substitute B into our equation and we get:
DutyCycle = C^(BP) -1
Now put in our second point to calculate the constant C.
100 = C^10 – 1
101 = C^10
C = tenth root of 101 = 1.5864
So, our final equation to calculate Duty Cycle is:
DutyCycle = 1.5864^(BP) – 1
With this equation we are not ready to develop our code. The video will step you through the code line by line.
import Adafruit_BBIO.GPIO as GPIO
import Adafruit_BBIO.PWM as PWM
from time import sleep
print "Button 1 Pushed"
print "Button 2 Pushed"
dutyCycle = 1.5864**(BP)-1