1

I'm attempting to turn on a set of LED's one at a time and then switch them all off at the same time, I am stuck however on turning them off at the same time.

That is my code:

int ledpins[] = {2,3,4,5,6,7,8,9}; //creates a list of the pins in use

void setup() {
  for (int i = 0; i < 8; i++){
    pinMode(ledpins[i], OUTPUT);  // iterates over the list led pins from the 0 pin to the pins before the eigth
  }  
}

void loop() {
  for (int i = 0; i < 8; i++){
    digitalWrite(ledpins[i], HIGH); // turns all the pins of one at a time
  }

  delay(100); //when all on will wait 100 ms
  digitalWrite(ledpins[0,7], LOW); //turns off all the leds at once
  delay(100);
}

The annotations are for my own understanding. I just need help turning all the LED's off at once which I dont know the command for.

2 Answers 2

3

You have already done it twice, why are you struggling the third time?

for (int i = 0; i < 8; i++){
  digitalWrite(ledpins[i], HIGH); // turns all the pins of one at a time
}

// turns all the pins of one at a time

Except that it is happening so fast you can't see then doing it individually. So just do the same but set them to LOW:

for (int i = 0; i < 8; i++){
  digitalWrite(ledpins[i], LOW); // turns all the pins off one at a time
}

Now you might want to add a delay into the loop that turns them on so you can see them turn on individually instead of all at once:

for (int i = 0; i < 8; i++){
  digitalWrite(ledpins[i], HIGH); // turns all the pins of one at a time
  delay(50);
}
1

There is another approach that is to use direct port manipulation. It is a lot faster than using digitalWrite in the sense that it requires less clock cycles to execute and allows you to change one port at a time (the UNO has 3 ports called D, B and C). You can find an introduction to port manipulation on this page: https://www.arduino.cc/en/Reference/PortManipulation

Here is an example that toggles the LED you chose:

void setup()
{
    DDRD |= B11111100; // Pin 2 to 7 as outputs
    DDRB |= B00000011; // Pin 8 to 9 as outputs
}


void loop()
{
    // Pin 2 to 7 HIGH
    PORTD |= ( 1<<2 ) | ( 1<<3 ) | ( 1<<4 ) | ( 1<<5 ) | ( 1<<6 ) | ( 1<<7 );
    // Pin 8 to 9 HIGH
    PORTB |= ( 1<<0 ) | ( 1<<1 );

    _delay_ms( 500 );

    // Pin 2 to 7 LOW
    PORTD &= ~( 1<<2 ) & ~( 1<<3 ) & ~( 1<<4 ) & ~( 1<<5 ) & ~( 1<<6 ) & ~( 1<<7 );
    // Pin 8 to 9 LOW
    PORTB &= ~( 1<<0 ) & ~( 1<<1 );

    _delay_ms( 500 );
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.