简体   繁体   中英

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);

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

char * itoa (int value, char *result, int base)
{
// check that the base if valid
if (base < 2 || base > 36) { *result = '\0'; return result; }

char* ptr = result, *ptr1 = result, tmp_char;
int tmp_value;

do {
    tmp_value = value;
    value /= base;
    *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
} while ( value );

// Apply negative sign
if (tmp_value < 0) *ptr++ = '-';
*ptr-- = '\0';
while (ptr1 < ptr) {
    tmp_char = *ptr;
    *ptr--= *ptr1;
    *ptr1++ = tmp_char;
}
return result;
}

Hope this would be helpful

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