如何从 MPU 陀螺仪发送的字节数组中获取整数

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

我正在尝试在 HTML 网站上读取 MPU 数据。我使用 MQTT 进行连接,使用 ESP8266 发送数据。这很好用,但我的问题是 esp 只是发送字节数组,我不知道如何将它们转换成数值。

这是 JavaScript 控制台在 MQTT 发送数据时向我显示的内容:

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

在我的代码中,我尝试将值转换为字符串,因为 MQTT 似乎不发送普通整数。

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);
char * itoa (int value, char *result, int base)
{
// check that the base if valid
if (base < 2 || base > 36) { *result = '[=10=]'; 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-- = '[=10=]';
while (ptr1 < ptr) {
    tmp_char = *ptr;
    *ptr--= *ptr1;
    *ptr1++ = tmp_char;
}
return result;
}

Hope this would be helpful

所有 MQTT 负载都是字节数组,这意味着它可以轻松传输任何东西。

您可以使用 paho 客户端从 HTML 页面中收到的字节数组中读取整数。您需要使用 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];

你可以在我的博客上找到一个例子here