led dimmer (PWM)

In the previous examples, we blink a led. Now we are going to use PWM (pulse width modulation), in order to make the led to change its color, slowly.





// dimmer led test with Pinguino (PWM example)

#define PIC18F4550

// pin where the led is connected
#define LED 11
// PWM pins only are the PIN 11 and 12.

void setup()


void loop()
  unsigned int a;

  for (a=0;a<1023;a++) {
  for (a=1023;a>0;a--) {

As this it's not the first pinguino example, we are going to suppose that you know what means the setup and loop functions, and why appears the #define PIC18F4550 di

The new function that we have used in this example, it's the analogWrite call. analogWrite receives two parameters: the pin number and the value that we want to set as "analog". In the previous example we use allways a constant value for the pin number (LED), and change the value. Value it's a 10bit number (a number between 0 and 1023).

PWM can
only be used in some determined pins. The only two pin that have PWM are 11 and 12.

How does PWM more or less work? In order to get a determined "analog" value, really the thing that happens it's that the microprocessor generates pulses, and the duration of these varied in order to get the correspondating value (this happens very quickly). Let's say that we do "analogWrite(LED,512)", 512 it's more or less the 50% of the total. Then you will get pulses in the pin, and half of the time will be on, and half of the time will be off. Then, if the pic has a power of 5V, in the pin you will get as if you where powering the pin with aproximally 2.5V. If instead of 512, you use 256, you will get 25% at 5V, and 75% at 0V, then you will get 1.25V... If you need more details about PWM you could search the pic datasheet.

In a PIC when you use PWM there is no need to
configure the pin as output, or input. That's the reason because there is no anything in setup routine.

What happens if you need more PWM pins. You could do it yourself by software (using interrupts). We will provide a example in the expert section soon.


- change delay to see what happen,
- change pin and modify the program to dimming the led on another pin (you can not use all the pins, only a few)
- try to connect a bi-color led to pins 11 and 12, and try to get diferent colors