简体   繁体   中英

How to combine uint8 and uint16 bytes in array with arduino?

I have complex variable byte array that I need send thru serial in arduino, Im using esp32 chip so I think I should have enough RAM to deal with it. But Im not sure how to do it, because some variables are uint8, some uint16 and I must send them in 1 piece thru Serial.write(). While all variable are uint8 I have no problems eg:

    void loop() {
    uint8_t oil_temp = 0xFF; //lets assume its variable, not constant
    uint8_t ambient_temp = 0xFF; 
    uint8_t coolant_temp = 0xFF;
    uint8_t interior_temp = 0xFF;
    uint8_t main_array[4] = {oil_temp, ambient_temp, coolant_temp, interior_temp};
    Serial.write(main_array, 4); // sends FF FF FF FF
  delay(1000);
}

Problem comes when I add uint16 variables

    void loop() {
    uint8_t oil_temp = 0xFF; //lets assume its variable, not constant
    uint8_t ambient_temp = 0xFF;
    uint8_t coolant_temp = 0xFF;
    uint8_t interior_temp = 0xFF;
    uint16_t engine_speed = 0xAAEE;
    uint8_t main_array[6] = {oil_temp, ambient_temp, coolant_temp, interior_temp, engine_speed};
    Serial.write(main_array, 6); // sends FF FF FF FF EE 00
  delay(1000);
}

If I try Serial.write(main_array, 5); it sends "FF FF FF FF EE"

I expect to get "FF FF FF FF AA EE" so I could easily parse it on other end. Please help

I think what is happening is the data from engine_speed is being mangled because its expecting uint8_t values throughout your assignment.

I would build main_array more explicitly to avoid issues like this.

 uint8_t main_array[6];
 main_array[0] = oil_temp;
 main_array[1] = ambient_temp;
 main_array[2] = coolant_temp;
 main_array[3] = interior_temp;
 main_array[4] = engine_speed >> 8;
 main_array[5] = engine_speed & 0xFF;

You can switch the assignments for 'main_array[4]' and 'main_array[5]' depending if you want to work big endian or little endian.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM