Go Down

Topic: all Pin PWM (Read 4366 times) previous topic - next topic


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..

Code: [Select]

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


Jul 31, 2010, 02:02 pm Last Edit: Jul 31, 2010, 02:13 pm by zaphil Reason: 1
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:

Code: [Select]

#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...


Go Up