PWM drive of an LED array

Hi Folks,

after googling arround with no right answer for me, i decided to post my (simple) question here.

When i setup an array with 6 LED on the PWM outputs like this,

int led[6]{3, 5, 6, 9, 10, 11};
void setup() {
for (int i=0; i<6; i++) {
pinMode(led*, OUTPUT);*

  • }...*
    i can switch easy all led on with this:
    void ledOn () {

  • for (int x=0; x<6; x++) {*

  • digitalWrite(led[x], HIGH); *

  • }*
    }
    also can fade a single led (out of the 6)with this
    void ledDrive () { //twinkle effect

  • int randnum = random(0, 6); //led nr*

  • int randnum1 = random(0, 254); //power*

  • int randnum2 = random(5, 100); //delay*

  • Serial.print("led nummer");*

  • Serial.println(randnum);*

  • for (int power=0; power<randnum1; power++) {*

  • analogWrite(led[randnum], power);*

  • //Serial.println(power);*

  • delay(randnum2);*

  • } *

  • for (int power=randnum1; power>1; power--) {*

  • analogWrite(led[randnum], power);*

  • //Serial.println(power);*

  • delay(randnum2);*

  • }*

  • digitalWrite(led[randnum], LOW);*
    }
    randomly in this case.
    Now i wonder how can i fade all led together? Must not be randomly for example.
    By the way i wonder why all led stay a little amount on in the function above. They only turn real off, since i added the "digitalWrite(led[randnum], LOW);" line ?
    THX for your reply`s
    Matthias

Hi MatthiaS;

I think it works this way:

for (int power=randnum1; power>=1; power--) {
analogWrite(led[0], power);
analogWrite(led[1], power);
analogWrite(led[2], power);
analogWrite(led[3], power);
analogWrite(led[4], power);
analogWrite(led[5], power);
//Serial.println(power);
delay(randnum2);
}

Do not mix analog output functions and digital output functions. If you do an analogWrite with a value of 0 the led should be off, there is no need for a digitalWrite to set this pin off!

good luck
Mike

HI Mike,

thx for the quick answer :slight_smile: I had an anticipation the solution must be easy. But my way of solving the problem has turned in the wrong direction..

Now I changed the power value (in the fade out) to 0 and commented out the "digitalWrite(led[randnum], LOW);" line temporarily.
The problem stays the same. The led s didn't turn realy off. They shine like pwm value 20 until the other randomly selected led is working.

void ledDrive () { //twinkle effect
int randnum = random(0, 6); //led nr
int randnum1 = random(0, 254); //power
int randnum2 = random(5, 100); //delay
Serial.print("led nummer");
Serial.println(randnum);

//fade in
for (int power=0; power<randnum1; power++) {
analogWrite(led[randnum], power);
//Serial.println(power);
delay(randnum2);
}
//fade out
for (int power=randnum1; power>0; power--) {
analogWrite(led[randnum], power);
//Serial.println(power);
delay(randnum2);
}
//digitalWrite(led[randnum], LOW);
}

Regards

Matthias