<- back to main Article

Simple Software PWM

This example is just for better understanding of PWM.
The shown method is not recommended for a complex Project.

/**************************************************************************************************
*
*   simpleSoftwarePWM_00
*
*   Version:      00 - Mai 2010
*   Author:       Tom Pawlofsky www.caad.arch.ethz.ch tom-DOT-pawlofsky-AT-arch-DOT-ethz-DOT-ch
*
*   Desc:         show how to implement a simple PWM signal by software
*
***************************************************************************************************/

/* note
this method is not recommended for any project, it is just to illustrate how PWM works
this method offers no frequency control on the PWM-Signal
this method uses a Byte that overflows -> 255 + 1 = 0
this might crash your Microcontroller in a more complex project
*/

byte counter = 0; // 0..255
byte duty; // duty/255 = % of duty
boolean flip;// 0-> off, 1-> on

int pinLed = 8; // use a Led as feedback - it will have different brightness for different duty-values

void setup(){
        duty = 64; // the duty-cylcle value 0..255, 64 correspond to 25% Duty
        flip = false; // init value for the Led Off(false)/On(true)

        // pinMode for pinLed
        pinMode(pinLed,OUTPUT);
}


// PWM with the 256th of the loop-frequency
// loop-frequency is mostly dependent on the amount of script the CPU has to do within
// you can add a delay to slow down the frequency and see a blinking Led
void loop(){
        // change the pin whenever counter == 0 or duty
        if (counter == 0 || counter == duty) {
                flip = !flip; // 0 becomes 1, 1 becomes 0
                digitalWrite(pinLed,flip);
        }
        // counter for next loop
        counter++; // 255 + 1 = 0
        // delay or  delayMicroseconds - if you want to see your Led blinken
        // try to avoid delay in your scripts !!!
        // delay(100);
}


<- back to main Article