簡體   English   中英

如何從MPU陀螺儀發送的字節數組中獲取整數

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

我正在嘗試在HTML網站上讀出MPU數據。 我正在使用MQTT進行連接,並使用ESP8266來發送數據。 這工作得很好,但是我的問題是esp只是發送字節數組,我不知道如何將它們轉換為數值。

這是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) 

在我的代碼中,我嘗試將值轉換為字符串,因為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);

所有MQTT負載都是字節數組,這意味着它可以輕松傳輸所有內容。

您可以使用paho客戶端從HTML頁面中接收的字節數組中讀取整數。 您需要使用類型化數組 ,並且使用哪種排序取決於您嘗試讀取的整數的大小。 假設您有2個字節,則可能是16位整數,因此您需要一個Int16Array

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

你可以在我的博客找到一個例子在這里

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

希望這會有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM