简体   繁体   English

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

[英]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. 我正在尝试在HTML网站上读出MPU数据。 I'm using MQTT for the connection and an ESP8266 to send the data. 我正在使用MQTT进行连接,并使用ESP8266来发送数据。 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. 这工作得很好,但是我的问题是esp只是发送字节数组,我不知道如何将它们转换为数值。

This is what the JavaScript console shows me when MQTT sends the data: 这是MQTT发送数据时JavaScript控制台向我显示的内容:

[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. 在我的代码中,我尝试将值转换为字符串,因为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);

All MQTT payloads are byte arrays, this means it can easily transport anything at all. 所有MQTT负载都是字节数组,这意味着它可以轻松传输所有内容。

You can just read the integers from the byte arrays you are receiving in the HTML page with the paho client. 您可以使用paho客户端从HTML页面中接收的字节数组中读取整数。 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 假设您有2个字节,则可能是16位整数,因此您需要一个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 希望这会有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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