Search code examples
c++carduinolora

Getting data into a uint8_t array (C/C++) on Arduino


I'm working in C/C++ on Arduino and am having trouble getting what I need into an array of type uint8_t. C/C++ is not a language I'm familiar with (I'm a python / php / basic guy), so I'm struggling with finding the right terms / docs at the moment.

Basically, the following is show in an example, and works:

static uint8_t mydata[] = "Hello";

I would later like to completely replace the contents of this with something else.

String Temp = "31.0";
String Hum = "60.0";
String Measurements = "";

Measurements = Temp + "C" + Hum + "H";
mydata[0] = ""; //Reset the array contents? Not sure.
uint8_t mydata[] = Measurements;

The above code example results in the following error from the compiler:

error: initializer fails to determine size of 'mydata'
uint8_t mydata[] = Measurements;
        ^~~~~~

error: array must be initialized with a brace-enclosed initializer
uint8_t mydata[] = Measurements;
                   ^~~~~~~~~~~~

initializer fails to determine size of 'mydata'

Any suggestions on how I can deal with this? The first instance where I see static uint8_t mydata[] = "Hello"; being used does not require the declaration of a size of the data. If I change to uint8_t mydata[0] = Measurements; then the length warning goes away, but I'm left with the message that an array must be initialised with a brace-enclosed initialiser.


Solution

  • For embedded code, compactness is the key. Use user-defined structure like so.

    struct Temperature{
      uint8_t temp[7];
      uint8_t humi[7];
      Temperature(){temp[0] = humi[0] ='\0';}
      Temperature(uint8_t * t, uint8_t *h){strcpy(temp,t); strcpy(humi,h);}
      void reset(){ temp[0] = humi[0] ='\0';}  
      void setTemp(uint8_t* t){strcpy(temp,t);}
      void setHum(uint8_t* h){strcpy(humi,h);}
      void print(){ char str[16]; sprintf(str,"Temp=%4.2f Hum=%4.2f", atof(temp), atof(humi)); Serial.println(str);}
      void operator=(Temperature other){ strcpy(temp,other.temp); strcpy(humi,other.humi);}
    };    
    
    void loop() {
      Temperature temp1;
      temp1.reset();
      temp1.setTemp("52.34");
      temp1.setHum("30");
      Temperature temp2;
      temp2 = temp1;
      temp2.print();
    }