Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
9 years, 5 months ago.
How do you update Characteristic Value with a string
I'm using an HRM-1017 device, the BLE_API library and notifications. I'm able to update the binary side of the package with the code below, but not how to add a string to the payload.
void updateValue(void){
double x = 0.0; double y = 0.0; double z = 0.0; i2c.read_xyz(&x, &y, &z);
memcpy(thermTempPayload+sizeof(double)*0, &x, sizeof(x));
memcpy(thermTempPayload+sizeof(double)*1, &y, sizeof(y));
memcpy(thermTempPayload+sizeof(double)*2, &z, sizeof(z));
pc.printf("%.3lf,%.3lf,%.3lf\r\n",
- (double*)&thermTempPayload[sizeof(double)*0],
- (double*)&thermTempPayload[sizeof(double)*1],
- (double*)&thermTempPayload[sizeof(double)*2]); ble.updateCharacteristicValue(ControllerChar.getValueAttribute().getHandle(), thermTempPayload, sizeof(thermTempPayload)); }
1 Answer
9 years, 5 months ago.
It should just be something like this:
int nextData = 0; char fixedString[] ="Hello"; char variableString[20]; // add the doubles memcpy(thermTempPayload+nextData, &x, sizeof(x)); nextData += sizeof(x); memcpy(thermTempPayload+nextData, &y, sizeof(y)); nextData += sizeof(y); memcpy(thermTempPayload+nextData, &z, sizeof(z)); nextData += sizeof(z); // add a constant string memcpy(thermTempPayload+nextData, fixedString, strlen(fixedString)+1); // +1 to include the null delimiter. nextData += strlen(fixedString)+1; // +1 to include the null delimiter. // add a generated string int stringLength = snprintf(variableString,20,"%.3lf",x); memcpy(thermTempPayload+nextData, variableString, stringLength +1); // +1 to include the null delimiter. nextData += stringLength +1; // +1 to include the null delimiter.
The way you were adding the doubles was fine but by using a variable that tracks how much data we have added rather than hard coding sizeof(double) * n it is a lot easier in the future if you want to change the order or add extra values in the middle of the structure. It also allows you to use the value of nextData to know the size of your data structure and verify you aren't about to run out of space in thermTempPayload.
For the string created using snprintf you could use strlen(variableString) and make the code identical to that for the fixed string, if you were to create an addString function that would be the way to do it, but since snprintf returns the length of the string it seems silly not to use it.