2

I need to loop through different Pins in an Uno board, specifically over Pin # 3,5,6,9,10,11. (The PWM ones). I know how to loop over consecutive Pins:

for (int thisPin = 2; thisPin <= 11; thisPin++) 
{
  pinMode(thisPin, OUTPUT);
}

I do not know how to create a list of just the Pins I want and loop though it.

2 Answers 2

7

Arduino nowadays even knows the c++ foreach version of loops

int pins[] = {3,5,6,9,10,11};

void setup(){
  for(int pin: pins){
    pinMode(pin, OUTPUT);
  }
}

Just as an addendum to @Roman 's correct answer.

Sign up to request clarification or add additional context in comments.

1 Comment

Good point, I like this
3

Create an array of the pins you want to work with and loop through that like this:

int pin[] = {3,5,6,9,10,11};

void setup() {

  //gets length of array
  int len = sizeof(pin)/sizeof(pin[0]);

  for(int i=0; i<len; i++){
    pinMode(pin[i], OUTPUT);
  }

}

You can choose to use len variable to make it easier to add or remove elements from the array as you're working with the code, or just set the size manually in the for loop

1 Comment

Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, can you edit your answer to include an explanation of what you're doing and why you believe it is the best approach?

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.