Concat one var into another

Currently I have a lot of code blocks structured like this:

if (cellNum == 0)                                      // read charging current
    cells[cellNum].current = (adc.readADC(cell1chargeCurrent) * voltageReference5v) / 1024;
else if (cellNum == 1)
    cells[cellNum].current = (adc.readADC(cell2chargeCurrent) * voltageReference5v) / 1024;
else if (cellNum == 2)
    cells[cellNum].current = (adc.readADC(cell3chargeCurrent) * voltageReference5v) / 1024;
else if (cellNum == 3)
     cells[cellNum].current = (adc.readADC(cell4chargeCurrent) * voltageReference5v) / 1024;

I would like to cut down the amount of if statements so i can reduce it to something like this:

cells[cellNum].current = (adc.readADC("cell" + (cellNum + 1) + "chargeCurrent") * voltageReference5v) / 1024;

So im trying to find a way to split the variable names likes “cell1chargeCurrent” and insert the variable “cellNum” to replace the ‘1’, therefore eliminating the need for repetition.

Are there any short ways of doings this? Main reason is wanting to reduce line count

You need to convert all the "cell*chargeCurrent" into an array. How you do that depends on the code you did not post :wink:

Oh believe me you dont want me to burden you with my 750 lines of pure mess :smiley:

Ive defined the cell*chargeCurrent variables in a config file like this:

// Analog expander pinout
#define cell1chargeCurrent  0
#define cell2chargeCurrent  1
#define cell3chargeCurrent  2
#define cell4chargeCurrent  3

An array makes so much more sense! So i can do something like?:

int cellChargeCurrent[] = { cell1chargeCurrent, cell2chargeCurrent, cell3chargeCurrent, cell4chargeCurrent }; 


cells[cellNum].current = (adc.readADC(cellChargeCurrent[cellNum]) * voltageReference5v) / 1024;

If "cell*chargeCurrent" always starts at zero and increases by one, you do not need any constant declarations:

cells[cellNum].current = (adc.readADC(cellNum) * voltageReference5v) / 1024;

Otherwise you should declare "cellChargeCurrent" as "const int" or "const byte" :slight_smile:

Well cell*chargeCurrent vars are just pin numbers where i measure the current from so they dont increment by 1. However, cellNum does start at 0 and increments by 1 as it all in one massive for loop

for (int cellNum = 0; cellNum < 4; cellNum++){ }

I have 4 batteries in my system and it monitors cell 1, loops to cell 2, 3, 4, updates display and starts again

But i should still make my vars that hold pin numbers as const vs. #define?

I would create an array of const byte to hold the pin numbers:

const byte CELL_CHARGE_PINS[] = { 0, 1, 2, 3 /* and so on */};

and code it as:

cells[cellNum].current = (adc.readADC(CELL_CHARGE_PINS[cellNum]) * voltageReference5v) / 1024;

Always remember to use descriptive names for constants and variables, most ppl use UPPERCASE for constants :slight_smile:

Will do! Thanks for your help