Help with using loops or functions to make code less dense

Hi good people!

I am currently going through the beginning stages of learning about coding for arduino circuits and keep running into the issue that my code feels extremely bulky as soon as I start doing something that is semi complicated to me.

For instance, I have built a circuit with a few LEDs that have essentially two main goals (this is just to try and get a better understanding of working with potentiometers and switches before building an Arduino based guitar pedal)

  1. Lights turn on two at a time based on the potentiometer reading (kinda like car racing start lights/traffic lights), then after the potentiometer reaches a certain resistance,
  2. The LEDs flash in sequence with a delay between each switching on and off based on the potentiometer reading.

My code is currently as follows, would really appreciate if someone could guide me to how to make this less bulky, as making this more complicated would likely lead to more mistakes and issues in the circuit.

// C++ code
//

int pot = A5; // Define potmeter wiper input as A5
int potValue = 0;	// Define default value of potmeter
int switch_pin = 2; // allocate switch to digital pin 2
int switch_state; // ??
int redled1 = 8; // Define redled1 input as Digital pin 8
int redled2 = 9; // Define redled2 input as Digital pin 9
int orangeled1 = 10; // Define orangeled1 input as Digital pin 10
int orangeled2 = 11;	// Define orangeled2 input as Digital pin 11
int greenled1 = 12; // Define greenled1 input as Digital pin 12
int greenled2 = 13; // Define greenled2 input as Digital pin 13
  
void setup()
{
  Serial.begin(9600); //Start serial monitor with 9600 baud
  pinMode(8, OUTPUT); //Define pin 8 as OUTPUT
  pinMode(9, OUTPUT); //Define pin 9 as OUTPUT
  pinMode(10, OUTPUT); //Define pin 10 as OUTPUT
  pinMode(11, OUTPUT); //Define pin 11 as OUTPUT
  pinMode(12, OUTPUT); //Define pin 12 as OUTPUT
  pinMode(13, OUTPUT); //Define pin 13 as OUTPUT
  pinMode(pot, INPUT); //Define pin A5 (potmeter) as INPUT
  pinMode(switch_pin, INPUT_PULLUP); //Define Switch pin as input
}

void loop()
{
  int switch_state = digitalRead(switch_pin); //Make variable read of switch and define switch state to read from pin
  int potValue = analogRead(pot); //Read analog value of potmeter
  int delayTime = map(potValue, 342, 1023, 100, 5); //Map lower end of resistor to higher delay between flashes
  
  Serial.println(potValue); //Enable printing of the pot value in Serial Monitor
  delay(100); //delay read (is this necessary??)

  if (switch_state==LOW) //If switch is off, do nothing
  {
    digitalWrite(13,0);
    digitalWrite(12,0);
    digitalWrite(11, 0);
    digitalWrite(10, 0);
    digitalWrite(9, 0);
    digitalWrite(8, 0);
  }
    else
    {
      
  if (potValue==0) //If pot Value is zero, keep LEDs off (Should this be removed given the function (term?) above?
  {
    digitalWrite(13,0);
    digitalWrite(12,0);
  }
  else if(potValue>0 && potValue<=113) //If pot Value is between x & y, switch on green LEDs and keep Orange and Red Off
  {
    digitalWrite(13, HIGH);
    digitalWrite(12, HIGH);
    digitalWrite(11, 0);
    digitalWrite(10, 0);
  }
  
  else if(potValue>=114 && potValue<=226) //If pot Value is between x & y, switch on green & Orange LEDs and keep Red Off
  {
    digitalWrite(11, HIGH);
    digitalWrite(10, HIGH);
    digitalWrite(9, 0);
    digitalWrite(8, 0);
  }
  
  else if(potValue>=227 && potValue<=341) //If pot Value is between x & y, switch on green, Orange & Red LEDs
  {
    digitalWrite(9, HIGH);
    digitalWrite(8, HIGH);
  }
 else if(potValue>=342 && potValue<=1023) //If pot value is between x & y, flash leds one and off based on potmeter reading
 {
   digitalWrite(13, HIGH);
   digitalWrite(12, LOW);
   digitalWrite(11, LOW);
   digitalWrite(10, LOW);
   digitalWrite(9, LOW);
   digitalWrite(8, LOW);
   delay(delayTime);
   digitalWrite(13, LOW);
   digitalWrite(12, HIGH);
   digitalWrite(11, LOW);
   digitalWrite(10, LOW);
   digitalWrite(9, LOW);
   digitalWrite(8, LOW);
   delay(delayTime);
   digitalWrite(13, LOW);
   digitalWrite(12, LOW);
   digitalWrite(11, HIGH);
   digitalWrite(10, LOW);
   digitalWrite(9, LOW);
   digitalWrite(8, LOW);
   delay(delayTime);
   digitalWrite(13, LOW);
   digitalWrite(12, LOW);
   digitalWrite(11, LOW);
   digitalWrite(10, HIGH);
   digitalWrite(9, LOW);
   digitalWrite(8, LOW);
   delay(delayTime);
   digitalWrite(13, LOW);
   digitalWrite(12, LOW);
   digitalWrite(11, LOW);
   digitalWrite(10, LOW);
   digitalWrite(9, HIGH);
   digitalWrite(8, LOW);
   delay(delayTime);
   digitalWrite(13, LOW);
   digitalWrite(12, LOW);
   digitalWrite(11, LOW);
   digitalWrite(10, LOW);
   digitalWrite(9, LOW);
   digitalWrite(8, HIGH);
 }
    }
}

Please keep in mind I am pretty much a beginner so my understanding of the intricacies of coding in C++ is limited, so there might be a few mistakes in the comments. Any and all corrections or suggestions would be greatly appreciated.

Welcome to the forum

As your topic does not relate directly to the installation or operation of the IDE it has been moved to the Programming category of the forum

You can start by putting the ledPins in an array and next write a function to switch one of the LEDs on.

// macro to calculate the size of an array of any type
#define NUMELEMENTS(x) (sizeof(x) / sizeof(x[0]))

// array for LED pins
uint8_t ledPins[] = { 8, 9, 10, 11, 12, 13 };

void setup()
{
  // set all LED pins to output
  for (uint8_t cnt = 0; cnt < NUMELEMENTS(ledPins); cnt++)
  {
    pinMode(ledPins[cnt], OUTPUT);
    // optional: make sure that all lLEDs are off
    digitalWrite(ledPins[cnt], LOW);
  }
}

void loop()
{
  // loop through all LEDs and switch them on indvidually
  for (uint8_t cnt = 0; cnt < NUMELEMENTS(ledPins); cnt++)
  {
    oneLedOn(cnt);
    delay(500);
  }
}

/*
Switch all LEDs off and switch the specified one on
In:
  led to be on; 0xFF will not switch a LED on
*/
void oneLedOn(uint8_t index)
{
  // all LEDs off
  for (uint8_t cnt = 0; cnt < NUMELEMENTS(ledPins); cnt++)
  {
    digitalWrite(ledPins[cnt], LOW);
  }
  // switch the specified LED on
  if (index != 0xFF)
  {
    digitalWrite(ledPins[index], HIGH);
  }
}

You use the function oneLedON() to replace a block like

      digitalWrite(13, HIGH);
      digitalWrite(12, LOW);
      digitalWrite(11, LOW);
      digitalWrite(10, LOW);
      digitalWrite(9, LOW);
      digitalWrite(8, LOW);

uint8_t is the same as a byte, it saves you a little bit of RAM if you use that for the LED pins instead of an int.

The loop() is a simple demo and does not do what you need;it's just as an example.
Code compiles but is not tested.

5 minutes hacking:

// C++ code
//

int pot = A5;         // Define potmeter wiper input as A5
int potValue = 0;     // Define default value of potmeter
int switch_pin = 2;   // allocate switch to digital pin 2
int switch_state;     // ??
int redled1 = 8;      // Define redled1 input as Digital pin 8
int redled2 = 9;      // Define redled2 input as Digital pin 9
int orangeled1 = 10;  // Define orangeled1 input as Digital pin 10
int orangeled2 = 11;  // Define orangeled2 input as Digital pin 11
int greenled1 = 12;   // Define greenled1 input as Digital pin 12
int greenled2 = 13;   // Define greenled2 input as Digital pin 13

int leds[] = {
   greenled2,
   greenled1,
   orangeled2,
   orangeled1,
   redled2,
   redled1
};

void setup() {
   Serial.begin(9600);  //Start serial monitor with 9600 baud
   for( auto led : leds ) {
      pinMode(led, OUTPUT);  //Define all LED pins as OUTPUT
   }
   pinMode(pot, INPUT);                //Define pin A5 (potmeter) as INPUT
   pinMode(switch_pin, INPUT_PULLUP);  //Define Switch pin as input
}

void loop() {
   int switch_state = digitalRead(switch_pin);        //Make variable read of switch and define switch state to read from pin
   int potValue = analogRead(pot);                    //Read analog value of potmeter
   int delayTime = map(potValue, 342, 1023, 100, 5);  //Map lower end of resistor to higher delay between flashes

   Serial.println(potValue);  //Enable printing of the pot value in Serial Monitor
   delay(100);                //delay read (is this necessary??)

   if( switch_state == LOW ) {  //If switch is off, do nothing
      for( auto led : leds ) {
         digitalWrite(led, LOW);
      }
   } else if( potValue == 0) {  //If pot Value is zero, keep LEDs off (Should this be removed given the function (term?   ) above?
      digitalWrite(greenled2, LOW);
      digitalWrite(greenled1, LOW);
   } else if( potValue <= 113 ) {  //If pot Value is between x & y, switch on green LEDs and keep Orange and Red Off
      digitalWrite(greenled2, HIGH);
      digitalWrite(greenled1, HIGH);
      digitalWrite(orangeled2, LOW);
      digitalWrite(orangeled1, LOW);
   } else if( potValue <= 226 ) {  //If pot Value is between x & y, switch on green & Orange LEDs and keep Red Off
      digitalWrite(orangeled2, HIGH);
      digitalWrite(orangeled1, HIGH);
      digitalWrite(redled2, LOW);
      digitalWrite(redled1, LOW);
   } else if( potValue <= 341 ) {  //If pot Value is between x & y, switch on green, Orange & Red LEDs
      digitalWrite(redled2, HIGH);
      digitalWrite(redled1, HIGH);
   } else {  //If pot value is between x & y, flash leds one and off based on potmeter reading
      for( auto ledOn : leds ) {
         for( auto ledOff: leds ) {
            digitalWrite(ledOff, LOW);
         }
         digitalWrite(ledOn, HIGH);
         delay(delayTime);
      }
   }
}

Magic numbers like this usually don't need to be created as variables, which occupy memory and can be changed. In this case, a plain enum would group the related int values, and simplify the names. Some extra symbols means it's not an automatic win to save keystrokes. But those symbols do make the code less dense visually; and you can discount the redundant comments, now that the code is pretty self-explanatory.

namespace Pin {
  enum LED {
    red1 = 8,
    red2 = 9,
    orange1 = 10,
    orange2 = 11,
    green1 = 12,
    green2 = 13,
  };
}

int leds[] = {
   Pin::green2,
   Pin::green1,
   Pin::orange2,
   Pin::orange1,
   Pin::red2,
   Pin::red1,
};

//...

      digitalWrite(Pin::green2, LOW);
      digitalWrite(Pin::green1, LOW);

Note that the namespace name Pin is used to group these, allowing names like green2 to be used for something else; and the type name LED is actually optional (in this usage).

As a bonus, in a decent IDE, if you type Pin::, code completion should suggest all seven possible names.

Thanks! This has helped quite a bit! My code even has a nicer aesthetic to it now

These for functions are an immense help with understanding some extra ones! Thank you so much

Ah okay! That makes sense. Will definitely also help when adding some extra things. Thanks!

I would also think about pot going down, so dim all higher LEDS in each step (and as you use delay(), the pot may change value to anything in the blocked time, so dim all higher LEDs).

So I would make function like this:

void setLEDlevel(int level){
  for (int i=0; i<NUMELEMENTS(ledPins); i++) digitalWrite(ledPins[i],i <= level); // i<=level is true(so HIGH) for lower LEDs and false(so LOW) for higher LEDs)
}

and then call it like

if (potValue<10) { setLEDlevel(-1) // allow for nearly-zero pot imperfection, dime all LEDs
else if (potValue<=113) {  setLEDlevel(2); }
else if (potValue<=226) {  setLEDlevel(4); }
else if (potValue<=341) {  setLEDlevel(6); }
else { /* do blinking */ } // so all cases covered

And less than five minutes for AI to exploit another language feature, case ranges:

Untested AI generated code:

// C++ code
//

int pot = A5;         // Define potmeter wiper input as A5
int potValue = 0;     // Define default value of potmeter
int switch_pin = 2;   // allocate switch to digital pin 2
int switch_state;     // ??
int redled1 = 8;      // Define redled1 input as Digital pin 8
int redled2 = 9;      // Define redled2 input as Digital pin 9
int orangeled1 = 10;  // Define orangeled1 input as Digital pin 10
int orangeled2 = 11;  // Define orangeled2 input as Digital pin 11
int greenled1 = 12;   // Define greenled1 input as Digital pin 12
int greenled2 = 13;   // Define greenled2 input as Digital pin 13

int leds[] = {
   greenled2,
   greenled1,
   orangeled2,
   orangeled1,
   redled2,
   redled1
};

void setup() {
   Serial.begin(9600);  //Start serial monitor with 9600 baud
   for( auto led : leds ) {
      pinMode(led, OUTPUT);  //Define all LED pins as OUTPUT
   }
   pinMode(pot, INPUT);                //Define pin A5 (potmeter) as INPUT
   pinMode(switch_pin, INPUT_PULLUP);  //Define Switch pin as input
}

void loop() {
   int switch_state = digitalRead(switch_pin);        //Make variable read of switch and define switch state to read from pin
   int potValue = analogRead(pot);                    //Read analog value of potmeter
   int delayTime = map(potValue, 342, 1023, 100, 5);  //Map lower end of resistor to higher delay between flashes

   Serial.println(potValue);  //Enable printing of the pot value in Serial Monitor
   delay(100);                //delay read (is this necessary??)

   if( switch_state == LOW ) {  //If switch is off, do nothing
      for( auto led : leds ) {
         digitalWrite(led, LOW);
      }
   } else {
      switch (potValue) {
         case 0 ... 113:  //If pot Value is between 0 and 113
            digitalWrite(greenled2, HIGH);
            digitalWrite(greenled1, HIGH);
            digitalWrite(orangeled2, LOW);
            digitalWrite(orangeled1, LOW);
            break;

         case 114 ... 226:  //If pot Value is between 114 and 226
            digitalWrite(orangeled2, HIGH);
            digitalWrite(orangeled1, HIGH);
            digitalWrite(redled2, LOW);
            digitalWrite(redled1, LOW);
            break;

         case 227 ... 341:  //If pot Value is between 227 and 341
            digitalWrite(redled2, HIGH);
            digitalWrite(redled1, HIGH);
            break;

         default:  //If pot value is between 342 and 1023, flash LEDs
            for( auto ledOn : leds ) {
               for( auto ledOff: leds ) {
                  digitalWrite(ledOff, LOW);
               }
               digitalWrite(ledOn, HIGH);
               delay(delayTime);
            }
            break;
      }
   }
}

Case ranges are relatively new but switch/case statements in general, are often a prettier alternative to if/else ladders.

a7 and chatGPT

And for blinking

will became

else { for (int i=0;  i<NUMELEMENTS(ledPins); i++) { setLED(i); delay(delayTime); }; };

AFAIK enums take up RAM and if yer not careful, use 16 bits each.

WHY?

If you want it read then test it yourself first!

look this over

const char *Version = "demonstrate use of functions and loops - 260922a";

const byte PinPot = A0;                          // Capitalize Constants
const byte PinSw  = 2;

const byte PinLed [] = { 13, 12, 11, 10, 9, 8 };
const int  Nled      = sizeof(PinLed);

enum { Off = HIGH, On = LOW };      // my LEDs are active LOW

unsigned long msec;

char s [90];

// -----------------------------------------------------------------------------
void ledsOff ()
{
    Serial.println (__func__);

    for (int n = 0; n < Nled; n++)
        digitalWrite (PinLed [n], Off);
}

// -----------------------------------------------------------------------------
// turn 2 leds on
void led2on (
    int  idx )
{
    Serial.println (__func__);

    for (int n = 0; n < Nled; n++)  {
        if (idx <= n && n <= (idx+1))
            digitalWrite (PinLed [n], On);
        else
            digitalWrite (PinLed [n], Off);
    }
}

// -----------------------------------------------------------------------------
// tune one LED on at a time in sequence
unsigned long msec0;
int           ledSeqIdx;

void ledSeq (
    unsigned long  msecDly )
{
    // used timer so function pot can be read while sequencer running
    if (msec - msec0 < msecDly)
        return;

    msec0 += msecDly;

    for (int n = 0; n < Nled; n++)  {
        if (ledSeqIdx == n)
            digitalWrite (PinLed [n], On);
        else
            digitalWrite (PinLed [n], Off);
    }

    if (Nled <= ++ledSeqIdx)
        ledSeqIdx = 0;

    sprintf (s, "seq: idx %d, msecDly %9lu", ledSeqIdx, msecDly);
    Serial.println (s);
}

// -----------------------------------------------------------------------------
int potValLst;

void loop ()
{
    msec = millis ();

    if (LOW == digitalRead (PinSw))  {
        ledsOff ();
        return;
    }

    int potVal = analogRead (PinPot);

    // avoid printing jittering values
    if (2 < abs(potValLst - potVal))  {
        potValLst  = potVal;
        Serial.println (potVal);
    }

    // map lower end of resistor to higher delay between flashes
    unsigned long  msecDly = map (potVal, 30, 60, 1000, 100);

    // check for lowest value first
    //        i have multi-turn pot so used small value 
    if (potVal < 10)
        led2on (0);

    else if (potVal < 20)
        led2on (2);

    else if (potVal < 30)
        led2on (4);

    else 
        ledSeq (msecDly);
}

// -----------------------------------------------------------------------------
void setup ()
{
    Serial.begin (9600);
    Serial.println (Version);

    for (int n = 0; n < Nled; n++)
        pinMode (PinLed [n], OUTPUT);

    pinMode (PinSw, INPUT_PULLUP);
}

Minor tips for arduino coding in general;

Serial.begin( 115200 ); will clear characters in the Serial Output Buffer (default 64 chars) 12x faster than .begin( 9600 ) by transmitting them out faster.

When making variables, don't use a 16 bit int where an 8 bit byte will do. Bytes can hold 0 to 255, pin numbers will fit. Arduino Uno has 2048 bytes of RAM and while 1 int won't ruin your day, the automatic int habit can have you making whole arrays of wasted bytes. It's just one habit to break going from PC to Arduino. Avoiding dynamic allocation is a habit to make in Arduino.

No, defining an enum itself does not use any RAM

they're like a #define or const. The compiler replaces the symbol in the code with the value

See if there isn't one copy that gets pointed to. I recall this from a ways back.

they're just constants.

do you think a 8-bit const byte is actaully stored in RAM and every time it is used a 32-bit pointer is used in its place.

AVR -- 16 bit pointers. AVR -- not a PC.

There have been threads about this, ASM was shown by west... the bootloader guy. What doesn't make sense to me is still at times true.

What I did learn was to specify type for enums.

that specifies the size of the consatnt, if it matches that value it is being assigne to and if it needs conversion, something lacking when using a #define

what ever ....

and using a pointer requires an additional operation to retrieve the value from RAM.