Setting multiple pi...
 
Notifications
Clear all

[Solved] Setting multiple pins as OUTPUT

7 Posts
5 Users
4 Reactions
3,991 Views
0
Topic starter

Hi,

I am using 8 digital pins to control the 8 LEDs separately. Instead of writing "pinMode(pin,OUTPUT)" for every other pin, is there any short method?


3 Answers
2

For loop will do the job if the pins are in series:

for (int i = 2; i <= 9; i++) { 
pinMode(i, OUTPUT);
}

If pins are random, use an array like this:

int buttons[]={2,4,5,8,10,13};
for(int i:buttons){
pinMode(i, OUTPUT);
}

 


Mehjabeen Topic starter 06/09/2024 6:22 am

@ankunegi Thank you. You are a life saver!!


1

You can use for loop for this; here's how

for (int i = 2; i <= 9; i++) { 
pinMode(i, OUTPUT);
}

This loop goes from pin 2 to 9 and sets each pin as OUTPUT. 

.


Mehjabeen Topic starter 10/05/2024 5:50 am

@jignesh What if the pins are not in series? For example 2,4,5,8,10,13.


Admin Admin 29/08/2024 7:21 am

@jignesh You can use an array: int buttons[]={2,4,5,8,10,13,}; for(int i:buttons){ pinMode(i, OUTPUT); }


1

Here's an example using a for loop to configure 8 digital pins (from pin 2 to pin 9) as outputs:

int ledPins[] = {2, 3, 4, 5, 6, 7, 8, 9}; // Array of pin numbers

void setup() {
  for (int i = 0; i < 8; i++) {
    pinMode(ledPins[i], OUTPUT); // Set each pin as an output
  }
}

void loop() {
  // Your code to control LEDs goes here
}

 

If the pins are not in a series, you can still use an array:

int ledPins[] = {2, 5, 7, 8, 10, 12, 13, A0}; // Array of specific pin numbers

void setup() {
  for (int i = 0; i < 8; i++) {
    pinMode(ledPins[i], OUTPUT); // Set each specified pin as an output
  }
}

void loop() {
  // Your code to control LEDs goes here
}

 


Share: