[SOLVED] Better way to code this

Hi Guys,

how do I make the bottom code do the top code?

void setup() {
  pinMode(1, INPUT_PULLUP);        //saves power on unused pins
  pinMode(2, INPUT_PULLUP);        //saves power on unused pins
  pinMode(4, INPUT_PULLUP);        //saves power on unused pins
  pinMode(5, INPUT_PULLUP);        //saves power on unused pins
}

I only want pins 1, 2, 4 and 5, the code below affects 1, 2, 3, 4, and 5.

void setup() 
{

  for (byte i = 1; i <= 5; i++)
    {
    pinMode (i, INPUT_PULLUP);    //saves power on unused pins
    }

how to exclude pin 3?

byte unusedPins[] = { 1, 2, 4, 5 };

void setup()
{

  for (byte i = 0; i < sizeof(unusedPins) / sizeof(unusedPins[0]); i++)
  {
    pinMode (unusedPins[i], INPUT_PULLUP);    //saves power on unused pins
  }
}

pcbbc:

byte unusedPins[] = { 1, 2, 4, 5 };

Shouldn't that be usedPins[] :slight_smile:

...R

const byte pullupPins[] = { 1, 2, 4, 5 };

void setup()
{
  for (auto pin : pullupPins)
  {
    pinMode (pin, INPUT_PULLUP);    
  }
}

or

void setup()
{

  for (byte i = 1; i <= 5; i++)
    {
    if (i == 3)  i++; 
    pinMode (i, INPUT_PULLUP);    //saves power on unused pins
    }
 }

TheMemberFormerlyKnownAsAWOL:

const byte pullupPins[] = { 1, 2, 4, 5 };

void setup()
{
 for (auto pin : pullupPins)
 {
   pinMode (pin, INPUT_PULLUP);    
 }
}

I had to look that construct up. C++ Range-based for loop (since C++11) Range-based for loop (since C++11) - cppreference.com

Well worth a karma point. !

Of course, it works without auto as well

for (uint8_t n : {1, 2, 4, 5})  pinMode ( n, INPUT_PULLUP);

Robin2:
Shouldn't that be usedPins[] :slight_smile:

According to the OPs comments I assumed not...

//saves power on unused pins

TheMemberFormerlyKnownAsAWOL:

const byte pullupPins[] = { 1, 2, 4, 5 };

void setup()
{
  for (auto pin : pullupPins)
  {
    pinMode (pin, INPUT_PULLUP);   
  }
}

Thanks guys, I tried them all and they were all good but went with this in the end.