Search code examples
javascriptcarduinobufferuint8t

Sending string as Uint8 buffer


I'm developing a mobile app to communicate with Bluetooth Module. I'm sending data through android app & receiving it on BLE module.

I'm using cordova & BLE central plugin for cordova to communicate with the device from android.

App seems to work fine but there is something wrong with Uint8 buffer.

ON THE APP PART :

I'm trying to send string as follow :

var data : 'action/523';

I'm using following function to convert string to array buffer before I finally send data to BLE device

function stringToArrayBuffer(str) {
    // assuming 8 bit bytes
    var ret = new Uint8Array(str.length);
    for (var i = 0; i < str.length; i++) {
        ret[i] = str.charCodeAt(i);
    }
    return ret.buffer;
}

var data = stringToArrayBuffer(data);
ble.writeWithoutResponse(app.connectedPeripheral.id, SERVICE_UUID, WRITE_UUID, data, success, failure);

ON THE DEVICE PART :

I'm using a simple device specific function to receive data on the BLE device as follow

void SimbleeBLE_onReceive(char *data, int len) {
     Serial.print(data); //prints 'action/523';
}

Now this works fine but later when I send string as follow

var data : 'action/3';

It just replaces first digit of the integer & append previous integer value 3[23] 'action/323/';

It happens every time I try to send 2 or more digit value first followed by lesser digit value later

Why so ? Is there anything such as buffer cache ?


Solution

  • On your devide part, it looks like you are receiving 2 datas:

    1. Raw data (char* non NULL terminated)
    2. Length of the data

    You should NULL terminate your received string

    void SimbleeBLE_onReceive(char *data, int len)
    {       
        char tmp[256]={0};
        strncpy(tmp,data,min(len,sizeof(tmp)-1));
        Serial.print(tmp);
    }
    

    This way, on your second call, you should see action/3 instead of action/323/