Dimming An LED With The RDK X5

In the last post we looked at how to light up an LED with minimal lines of code. To summarize, a GPIO pin is like an on/off switch. It either has no voltage or 3.3V which drives the LED to turn on or off.
Let There Be (A Dimming) Light!
Let's take this a bit further and convert this into a dimming circuit. At the end of this experiment, the LED will increase and decrease in brightness as though there was a dimming switch.
Hardware
Unlike in the earlier experiment, the pin has moved from GPIO pin 37 to GPIO pin 33 which is NOT a GPIO pin but a PWM pin. The rest of the circuit remains the same.
The X5 has two PWM pins. You can use either. I've used Pin 33.
Software
The goal as stated earlier is to get to the point in as few steps as possible. The code below will increase the brightness of the LED.
echo 1 > /sys/class/pwm/pwmchip0/export
echo 1000000 > /sys/class/pwm/pwmchip0/pwm1/period
echo 0 > /sys/class/pwm/pwmchip0/pwm1/duty_cycle
echo 1 > /sys/class/pwm/pwmchip0/pwm1/enable
for d in 100000 300000 500000 700000 900000; do
echo $d > /sys/class/pwm/pwmchip0/pwm1/duty_cycle
sleep 1
done
echo 0 > /sys/class/pwm/pwmchip0/pwm1/enable
echo 1 > /sys/class/pwm/pwmchip0/unexport
Don't worry about what the code is doing for now. Get it to work first and then read the explanation below.
Explanation
Dimming is done using an algorithm called PWM - Pulse Width Modulation. It is literally and figuratively an illusion. The dimming is not happening by adjusting the voltage (which is actually a complex problem), but by tricking our eyes into thinking the LED is dimming.
Tell Me More...
Imagine you are standing next to a light switch. When it is on the room is 100% bright. When it is off, there is 0% power and the room is dark.
Now imagine flipping the switch on and off incredibly fast at equal intervals. This will result in the room being lit with 50% brightness although the power to the bulb is the same. By changing the amount of time the switch is in the ON state compared to the OFF state, you can control the 'dimness' of the room. ON state at 75% of the time, brighter room. ON state 25% of the time, dimmer room.
This is essentially PWM. There are two variables in PWM:
Duty Cycle - How long the power stays ON
Period - Total time of ON and OFF state per cycle
In the code above:
Period: 1,000,000 ns
Duty Cycle is varied from
100,000 ns (10% brightness)
300,000 ns (30% brightness)
500,000 ns (50% brightness)
700,000 ns (70% brightness)
900,000 ns (90% brightness)
As you can tell, Duty Cycle cannot be more than the Period.
If you understood this explanation, go back to the code and you should be able to translate what it is doing.
In the next post, let's try something even more interesting!




