1

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);
gre_gor
  • 6,669
  • 9
  • 47
  • 52
Lennard
  • 25
  • 1
  • 4

2 Answers2

0

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

hardillb
  • 54,545
  • 11
  • 67
  • 105
-3
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

JDP
  • 56
  • 2
  • 10
  • 2
    Code without any explanation what it does, is not helpful. – gre_gor Jan 22 '18 at 13:09
  • This code is about integer to Ascii conversion. One can convert all possible integer including negative value into string easily. – JDP Jan 22 '18 at 14:34
  • @gre_gor I am a newbie for SO, sorry for the inconvenience.Thanks! – JDP Jan 22 '18 at 14:36