c++mqttesp8266mpu

How to get an integer from a byte array which was send from an MPU gyroscope


I'm trying to read out MPU data on an HTML website. I'm using MQTT for the connection and an ESP8266 to send the data. This works pretty good, but my problem is that the esp is just sending byte arrays and I don't know how to convert them into numeric values.

This is what the JavaScript console shows me when MQTT sends the data:

[Log] Buffer [51, 50] (2) 
[Log] Buffer [51, 50] (2) 
[Log] Buffer [51, 50] (2) 
[Log] Buffer [51, 50] (2) 
[Log] Buffer [51, 50] (2) 
[Log] Buffer [51, 50] (2) 

In my code I try to convert the values into strings, because it seems that MQTT doesn't send normal integers.

if (myMPU.readByte(MPU9250_ADDRESS, INT_STATUS) & 0x01)
{
  myMPU.readAccelData(&myResultAcc);
}

myMPU.updateTime();

//myResultAcc.printResult();
//myResultGyro.printResult();
//myResultMag.printResult();

//i think this converts a undefined value into a string
char str[12];
sprintf(str, "%d", myResultAcc);
Serial.println(str);
client.publish("esp/gyro",str);
Serial.println();

delay(600);

Solution

  • All MQTT payloads are byte arrays, this means it can easily transport anything at all.

    You can just read the integers from the byte arrays you are receiving in the HTML page with the paho client. You need to use Typed Arrays and which sort you use will depend on the size of the integer you are trying read. Given it looks like you have 2 bytes then it's probably a 16bit integer so you'll need a Int16Array

    var intArray = Int16Array.from(buffer);
    var value = intArray[0];
    

    You can find an example on my blog here