all Pin PWM

Hi everybody,

a little quick question....
I´m building a controller for dimmabable lghts controlled over midi...

the thing is, arduino only has a number of PWM ports. perfect I know that. since i need more i wrote a little custom Pwm script where I delay the script microseconds for a part of a fixed cycle..

void analoogUit(int val)//val between 0 en 1024
  if(val > 0)
      digitalWrite(ledPin, HIGH);  
      delayMicroseconds((cycle / 1024)*val);           
      digitalWrite(ledPin, LOW);   
      delayMicroseconds(cycle - ((cycle / 1024)*val)); 
     digitalWrite(ledPin, LOW);  

the problem is, It works like a charm, where is the catch? why have not all the pins PWM if within 6 lines of code I can "program" one?

I really dont get it...
willl this horrably fail with more pins, will i toast my arduino doing this?

thanks in advance

This won't do any physical harm but...

The catch is it will only work for a single pin!
... and also won't let anything else in the main loop work reliably. This is because you time delays will delay everything in the loop, and anything else you add with delays in it will interfere with what you have in this bit too.

A method I use for multiple uncritical and asynchronous delays is:

#define TIME1 900
#define TIME2 1030

void setup(){
  unsigned long Now;
  unsigned long delay1;
  unsigned long delay2;

void loop() {
  now = micros(); // saves keep calling an 'expensive' routine
  if(now - delay1 > TIME1){ // correctly handles zero rollround
    delay1 = now + TIME1;
    // your first code
  if(now - delay2 > TIME2){
    delay2 = now + TIME2;
    // your second code
  // your less time critical code

Your most time critical routine should be the first one, as each will add a small but unknown variable delay to the following ones. However, the average times work out very good in practice.

thanks for the response, you´re right... it doesnt work in a proper way, actually a second Led still kinda works, with a third one added it starts visibly blinking...

i´ll give your code a try...

Here you go:
Google Code Archive - Long-term storage for Google Code Project Hosting. :slight_smile:


great, thanks..!!