I need to fade 40 leds with an arduino mega and thought I could use it`s digital pins somehow. After some research I found this code on an old thread. I tried to modify it to stop the loop and go to the next pin but my knowledge is not good enough to do that. Can someone help me out?
It's better if you post your code, rather than attach it. And it must be posted between code tags. </> in the "Reply" dialog.
When it's just attached, we have to first create a folder then open your code in our IDE. And afterwards, the folder remains unless we navigate to the "Temp" folder and manually remove it. It's much easier to just view the code in your post.
What I wold like to achieve is to fade a led in then out. Than fade another one in and then out and so on. Maybe even fade the next one in while the other one is fading out " Tried to use break and while with no luck...
</>
int ledPin = 13;
unsigned int i = 0;
boolean rise = true;
int period = 1000;
void setup()
{
pinMode(ledPin, OUTPUT);
}
void loop()
{
if (i == period)
{
i = 1;
rise = !rise;
}
if (rise == false)
{
digitalWrite(13, LOW);
delayMicroseconds(i);
digitalWrite(13, HIGH);
delayMicroseconds(period - i);
i = i + 1;
}
if (rise == true)
{
digitalWrite(13, LOW);
delayMicroseconds(period - i);
digitalWrite(13, HIGH);
delayMicroseconds(i);
i = i + 1;
Programming is not like buying a lottery ticket. No luck is involved. Logic is.
There are no break or while statements in that mis-posted code.
Put all of the code in loop() now in a for loop that iterates from the lowest pin number to the highest pin number. Change the 13 that appears in 3 places to the for loop index variable's name.
void loop()
{
for(byte b=lowestPinNumber; b<=highestPinNumber; b++)
{
if (i == period)
{
i = 1;
rise = !rise;
}
if (rise == false)
{
digitalWrite(b, LOW);
delayMicroseconds(i);
digitalWrite(b, HIGH);
delayMicroseconds(period - i);
i = i + 1;
}
if (rise == true)
{
digitalWrite(b, LOW);
delayMicroseconds(period - i);
digitalWrite(b, HIGH);
delayMicroseconds(i);
i = i + 1;
}
}
}
One trick you can use is attach an ISR to a PWM pin and use that to drive a pin given
by a volatile variable. The PWM pin provides the timing, the variable identifies the pin.
Mega pins 2, 3 each are both PWM pins and interrupt pins (channels 0, 1)
something like:
void setup ()
{
attachInterrupt (0, handler, CHANGE) ; // ie pin 2
}
volatile byte led_pin = 13 ; // the variable nominating current LED pin
void handler ()
{
digitalWrite (led_pin, digitalRead (2)) ;
}
void loop ()
{
for (int i = 0 ; i < 255 ; i++)
{
analogWrite (2, i) ;
delay (20) ;
}
for (int i = 255 ; i > 0 ; i--)
{
analogWrite (2, i) ;
delay (20) ;
}
// here change led_pin but remember to turn it off when moving to a new pin as ISR
// might leave the old pin on or off depending on timing.
}