11 years, 7 months ago.

One function for all analog inputs

Hallo!

i have a queastion about the analog inputs. To read all analog inputs i have normaly to write for everyone input a little function. After reading i will show all values on an lcd display. All of this function are not long, but i have to write 5 time all of them. That makes me crazy..

 #include "mbed.h"
 #include "TextLCD.h"

  
 TextLCD lcd(p5, p6, p7, p8, p9, p10, TextLCD::LCD20x2); // rs, e, d4-d7 , type=LCD20x2
 AnalogIn voltage1(p15);voltage2(p16);voltage3(p17);voltage4(p18);voltage5(p19);voltage6(p20);
 
 
/* float read_out_chan(int &channel)
 {
    AnalogIn value(channel);
    return value.read();
 }*/
  
 int main() 
{
    while(1)
    {
         lcd.printf("Voltage1: %2.4f\n", voltage1.read());
         lcd.printf("Voltage2: %2.4f\n", voltage2.read());
         lcd.printf("Voltage3: %2.4f\n", voltage3.read());
         lcd.printf("Voltage4: %2.4f\n", voltage4.read());
         lcd.printf("Voltage5: %2.4f\n", voltage5.read());
         lcd.printf("Voltage6: %2.4f\n", voltage6.read());
     }
}

My question is: Is it possible to write one function for all channels. May be like:

*channel=p20;

 float read_out_chan(int &channel)
 {
    AnalogIn value(channel);
    lcd.printf("Voltage: %2.4f\n", value.read());
    return value.read();
 }

//P.S.: this code doesn't work

Sorry for my english....

1 Answer

11 years, 4 months ago.

You don't need to have a function if you don't want. An array of AnalogIns that you can loop over would suffice.

#include "mbed.h"
#include "TextLCD.h"

TextLCD lcd(p5, p6, p7, p8, p9, p10, TextLCD::LCD20x2); // rs, e, d4-d7 , type=LCD20x2
AnalogIn ain[] = {p15, p16, p17, p18, p19, p20};

int main()
{
    while(1) {
        for (int i=0; i < 6; i++) {
            lcd.printf("Voltage%d: %2.4f\n", i+1, ain[i].read());
        }
    }
}

There's no need for duplicate objects (standalone and in the array). This works too:

AnalogIn ain[] = { p15, p16, p17, p18, p19, p20 };
posted by Igor Skochinsky 13 Mar 2013

Igor, I thought something like that should be possible. Thanks.

posted by Stephen Paulger 13 Mar 2013

Arrays,

that is a god idea. Thank you very much.

posted by Andy T 13 Mar 2013