Sending Custom Data from DK to Gateway Shield


Hi all,

I am trying to send a string data from DK (firmware 2.2.50) to GW shield using typecasting as:

On DK Side:

String t, h, tt, hh;
  t = "TEMP:";
  h = ", HUM:";
  tt = String(temp_floating_pt);
  hh = String(humidity_floating_pt);
  String p =  t + tt + h + hh ;

  pi = (char*)p.c_str(); 
  uint8_t *data = (uint8_t *)pi;
 BLE.sendData(data, sizeof(data));

And on the GW Shield Side:

  void handle_custom_data( uint8_t *data, uint16_t length) {
    //if you use BLE.send from any connected DK, the data will end up here
    String d = String((char*)data);
    Particle.publish("Bluz Custom Data",d);

The Electron ends up publishing this:


Any idea where I might be going wrong??

Much appreciate the help!


Just glancing at it, I would say this part may be an issue:

  pi = (char*)p.c_str(); 
  uint8_t *data = (uint8_t *)pi;

What this does is create an array of char characters that is null terminated and returns a pointer to it. Then, another pointer is assigned that value. Calling sizeof on pi would then, I beleive, simply return the size of the pointer, and not the underlying array.

I beleive you want to change your sizeof call to .length() of the string This should give you the proper length of the string you are trying to send. Further, you can collapse some of this code easily:

  BLE.sendData((uint8_t *)p.c_str(), p.length());


Thanks, @eric. I made the changes you suggested and now I get this:

Any thoughts on what the issue might be?


So, I got garbage values for about the first 5-8 minutes after uploading the firmware onto the Bluz DK and then it settled down and started publishing expected string. After about ten minutes, it went back to publishing garbage values. Curious to find out what’s happening…


Sounds like the null character is not in the array when converted back to a string in the Electron. That constructor is expecting a c-style string, which is always null terminated. So when you call:

String d = String((char*)data);

there is no null character at the end of data. The String constructor attempts to use strlen to build the object, and it can’t work since there is no null character at the end.

The easiest way to fix it would be to include the null character in the data that gets transmitted from the DK. You can change the line in bluz to this:

BLE.sendData((uint8_t *)p.c_str(), p.length()+1);

That should include the null character all the way through to the Electron and then it will convert to a String properly. Let me know if that fixes it.


Adding the 1 to the length of the string fixed it. Thank you :slight_smile: