Tutorial 03 – Varying the brightness of a LED

The varying the brightness of a LED tutorial demonstrates the use of the For-Next and PWM commands with varying pulse length. It uses the PICAXE School Experimenter Board circuit diagram layout and configuration.

Tutorial Task
Dim the red LED from a full on state to an off state over a period of time. When the red LED is switched off increase the brightness over time until the red LED is switched on again.


Tutorial Solution 
How do one dim a LED in a digital environment where the LED is either ON or OFF? The answer is you must switch it very fast on and off and decrease the time it is switched on and increase the time it is off. 

Open a new program window in the PICAXE Programming Editor for your Running LED’s program and enter the initiation part of the code. In this section of the code all the variables are renamed with the symbol command and understandable names is assigned to make it easy for us to follow the program flow.

init:                                                                     ;Initiation part of the code
            symbol YELLOW_LED=1                  ;Rename port 1 to YELLOW_LED
            symbol Counter=b0                            ;Rename b0 variable to Counter

Enter the next part of the program into the editor.

main:                                                                 ;The main part of the code

           For Counter = 255 to 0 step -1          ;Start with a full on duty cycle and decrease
                   PWM 1, Counter, 1                       ;Send one puls out on port 1 decrease duty cycle
           Next Counter                                        ;Increment Counter and loop back
           For Counter = 0 to 255                       ;Start with a full off duty cycle and increase
                   PWM 1, Counter, 1                      ;Send one puls out on port 1 increase duty cycle
           Next counter                                        ;Increment the counter and loop back
           goto main                                              ;Loop back to main
           End                                                        ;End of program

The program uses the PWM (Pulse Width Modulation) command to change the pulse duty cycle. The LED is switched on for the full pulse if the duty variable is 255. The duty cycle is then decreased in increments of one until the LED is switched off for the whole pulse. Once that happens the process is then executed in reverse to slowly switch on the LED again.

What do you notice if you look at the dimming of the LED?

The dimming of the LED is not linear and it quickly dims near the end of the cycle.

You can download the program file, Tutorial 3 – Varying the brightness of a LED by right clicking on it and selecting ‘save link as’ from the popup menu.