how to include iteration variable in string wich in turn is used to call a function

I tried many google finds about int to string, sprintf and other but I did not manage to get this working. Hopefully someone here can help me out?

I have a unkown amount of onewire sensors. I can get the address and access them one by one, but I really want to rewrite this into a for loop, so I can run the functions for the exact amount of sensors connected.

The function I am calling is:
 
void printAddress(DeviceAddress deviceAddress,int senscount)


The sensors library:
 
typedef uint8_t DeviceAddress[8];


And in main.c I have:
1
2
3
4
5
6
7
8
9
10
11
// arrays to hold device addresses
DeviceAddress Sens01,Sens02,Sens03,Sens04,Sens05,Sens06,Sens07,Sens08,Sens09;

uint8_t buffer [50];
int n;
for (uint8_t i = 1; i < 9; i++)
{
   // show the addresses we found on the bus
   sprintf(dispbuf,"Device %d Address: ",i);
   Serial.print(dispbuf);
   printAddress(buffer,1);


This code does compile, but I get the wrong data printed.
Other attempts always get met a type conversion error.

What is a proper way to do this?



This is unrelated to your question, but you have undefined behavior. The printf() line should be
 
sprintf(dispbuf,"Device %d Address: ", (int)i);


As for your question:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
DeviceAddress *addresses[] = {
    &Sens01,
    &Sens02,
    //etc.
};

for (uint8_t i = 0; i < 9; i++)
{
    // show the addresses we found on the bus
    sprintf(dispbuf,"Device %d Address: ",i);
    Serial.print(dispbuf);
    auto buffer = addresses[i];
    printAddress(*buffer,1);
}
Last edited on
Thanks!
I got it working great now.
Will continue my Plural C++ course and review what you showed me.
Topic archived. No new replies allowed.