Multiple LED attenuation with Arduino

I need to figure out how to fade out and exit multiple LEDs in function with Arduino. It is not possible to use delay () because other things must be triggered while the light is dying. This is what has been so far, but does not work.

int value = 0; // variable to keep the actual value int ledpin = 9; // light connected to digital pin 9 int p1 = 0; void setup() { // nothing for setup Serial.begin(9600); } void loop() { inout(50, 30, 9, 0, 0); //inout(20, 20, 10); } void inout(int inDelay, int outDelay, int ledpin, long previousmil, int done) { if(millis() - previousmil>inDelay){ if (value <=255){ analogWrite(ledpin, value); // sets the value (range from 0 to 255) value+=5; } previousmil=millis(); } if(value = 260) done = 1; if(millis() - previousmil>outDelay && done == 1){ if (value >0){ analogWrite(ledpin, value); // sets the value (range from 0 to 255) value-=5; } previousmil=millis(); } } 
+4
source share
3 answers

The only obvious thing is that you have a status flag for which you can increase the value, but you do not test it in the first if. It would be better to structure your code a bit more. You can also track more than one value if you have more than one output, unless they all disappear and exit at the same time. In this case, you will be better off with an array of struct with parameters for each pine.

One way to use delay with multiple tasks is to have each task run for the time that has elapsed since the last cycle and set the delay at the end of the cycle to the time it takes to complete the tasks. If your loop looks something like this:

 static unsigned long last_time = 0; // set to millis() in setup static unsigned long refresh_period = 20; // 50Hz void loop() { unsigned long time = millis(); unsigned long delta = time - last_time; doTask1( delta ); doTask2( delta ); doTask3( delta ); doTask4( delta ); // as tasks may have taken some millis, adjust delay unsigned long post_time = millis(); if ( post_time - last_time < refresh_period ) delay( refresh_period - ( post_time - last_time ) ); last_time = time; } 

Then each task will be executed approximately every 20 ms and will be transmitted 20 or so how many milliseconds to update their status. This way you get some delay, but everything has a chance to update.

+6
source

Speculation, but this seems wrong:

 if(value=260) 

( reminding me of the last mistake of the worlds in C )

+1
source

If you want to quit equipment on this issue, you can connect your LEDs to an external controller chip, such as the TI TLC5940. This allows you to program the brightness level for each LED and process the PWM output to the LEDs separately from the ATMega processor in Arduino. You only need to reprogram the TLC chip if you want the brightness level to change. There is a good TLC library for handling chip communications in Google Code.

0
source

All Articles