-1

I am a C# dev and these C++ data conversions are killing me.

I have an Arduino sending binary data through LoRaWAN to AzureIOT. I am trying to decode my Temp/Humid/Bat payload that I am pulling out of AzureIOT Hub.

Here is a sample method I am using in C# to parse the byte array. Once I have parsed it, how do I convert those numbers back to their actual values?

Here is the input data on the sensor side:

T=74.48

RH=45.20

BatteryVoltage:3332

Thanks. Here is how the data was input:

float temperature = readDHTTemperature(); //this method prints T to Serial
float humidity = readDHTHumidity(); //this method prints H to Serial
uint16_t batteryVoltage = readBattery(true);
delay(100);

unsigned char *puc;

puc = (unsigned char *)(&temperature);
appDataSize = 10;
appData[0] = puc[0];
appData[1] = puc[1];
appData[2] = puc[2];
appData[3] = puc[3];


puc = (unsigned char *)(&humidity);
appData[4] = puc[0];
appData[5] = puc[1];
appData[6] = puc[2];
appData[7] = puc[3];

appData[8] = (uint8_t)(batteryVoltage>>8);
appData[9] = (uint8_t)batteryVoltage;

Here is the output:

private static void BytesToString()
{
    var hexStringFromPayLoad = "MzOYQgAAHEINBA==";
    var bytes = Base64Decode(hexStringFromPayLoad);

    Console.WriteLine($"Temp: {bytes[0]}, {bytes[1]}, {bytes[2]}, {bytes[3]}");
    Console.WriteLine($"Humid: {bytes[4]}, {bytes[5]}, {bytes[6]}, {bytes[7]}");
    Console.WriteLine($"Bat: {bytes[8]}, {bytes[9]}");

    /*
    Temp: 51, 51, 152, 66
    Humid: 0, 0, 28, 66
    Bat: 13, 4
    */
}
4
  • what is the received payload data, in hex?
    – jsotola
    Commented Sep 16, 2023 at 1:51
  • stackoverflow.com/questions/26310249/…
    – jsotola
    Commented Sep 16, 2023 at 2:42
  • @jsotola, sorry, I updated my post iwth the input and the CSV output. Thank you for your help.
    – Terrence
    Commented Sep 16, 2023 at 3:37
  • I edited the question to remove the word “decimal”, which you were misusing here. Commented Sep 17, 2023 at 12:06

1 Answer 1

1

Arduinos use very standard formats for their internal binary representations of data:

This is the same as your typical x86_64. The implication is that, once the bytes are in your PC, you do not need to perform any conversion at all. All you need to do is either alias or copy the bytes to the memory locations of the variables that are meant to get the values.

Example in plain C:

uint8_t temperature_bytes[] = { 51, 51, 152, 66 };
float temperature;
memcpy(&temperature, temperature_bytes, sizeof temperature);
// now `temperature` holds the value 76.1.

How you would do this in C# is a question that is out of topic in this site.

1
  • Good point. Thanks for the guidance. I will move over to overflow.
    – Terrence
    Commented Sep 17, 2023 at 15:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.