Storing and retrieving data in array's... I think!

I think I need help with arrays.

Im working with the ADS1115 and have started to think about the Gain function, specifically how I can code it efficiently.

Essentially, the Gain is set based upon a maximum input voltage to the ADS1115, like this:

Gain Values (Set for maximum input voltage):

0 : 6.144V
1 : 4.096V
2 : 2.048V
3 : 1.024V
4 : 0.512V
5 : 0.256V

Currently my code simply states:

gain_value = 1
max_inp_volts = 4.096

…and then I use these values elsewhere in the code.
In my case though, the maximum input voltage is derived from another function that is dependant on another variable (water tank height). I would like to be able to say something like:
if water_tank_height = x, then gain_value = 4 and max_inp_volts = 0.512

I can fathom the logic to establish what the gain_value should be, but dont know how to efficiently and automatically call the correct gain_value and max_inp_volts.

I could do it in a series of if, then, else statements but that seems very inefficient.

Any thoughts guys?


Is something like this what you are looking for ?
When water height is ‘whatever’ 10 in this case gain is set to 4 and the 4th element of the array is the volts (0.512).

const float inp_volts[6] = { 6.144, 4.096, 2.048, 1.024, 0.512, 0.256};
int gain_value = 0;
int water_tank_height = 0;

void setup() {

void loop() {

if (water_tank_height == 10) { gain_value = 4; }
max_inp_volts = inp_volts[gain_value];

1 Like

Wow, that was quick! Many thanks, that looks great.

I had it in my mind that the gain_value and the inp_volts needed to be in the array and therefore would need some kind of look-up.

This way looks simpler and just as good:)