Home > Net >  BLE Characteristic will not accept an int value
BLE Characteristic will not accept an int value

Time:12-09

I can't seem to pass an integer value over BLE.

I'm using the #include <ArduinoBLE.h> Arduino library.

The value sent keeps getting converted down to 8bit?

I've tried a number of things like changing the BLE Characteristic to Int (BLEIntCharacteristic) and Char (BLECharCharacteristic) but this has no effect.

Thanks in advance.


void loop() {

int reading;
  
{
  BLEDevice central = BLE.central();

  if (central) 
  {
    digitalWrite(LED_BUILTIN, HIGH);

    while (central.connected()) {
  
     reading = adc.readFB(0, 2.5, 500000.00);
  

serviceCharacteristic.setValue(reading); //reading value from load sensor is eg ; 89943


      
      Serial.print(reading);
       Serial.print('\n');
      //delay(200);
    }
  }
  digitalWrite(LED_BUILTIN, LOW);
}

CodePudding user response:

The data type of a Bluetooth LE characteristic is always an array of bytes. It is the task of your software to create an appropriate serialization.

On Arduino systems there are conversions to do this. Example:

uint8_t byteArray[2];
int intValue = 42;

byteArray[0] = [highByte(val);
byteArray[1] = lowByte(val);

intValue = word( byteArray[0], byteArray[1]);

But note the Endianess. On different computer systems, larger types of data are stored in different orders, so these orders must be taken into account when reassembling the data.

Reference:

CodePudding user response:

OK I finally figured it out with the help of these sites which I would really recommend reading:

Quick Bird Studios How to Read BLE Characteristics in Swift

Unsafe Territory! Understanding Raw Bytes and Pointers in Swift

This stack overflow post

On the Arduino side this is my code:

...
BLEIntCharacteristic serviceCharacteristic(CHARACTERISTIC, BLERead | BLENotify);
...

int reading;
  
{
  BLEDevice central = BLE.central();

  if (central) 
  {
    digitalWrite(LED_BUILTIN, HIGH);

    while (central.connected()) {
  
     reading = adc.readFB(0, 2.5, 500000.00);
  

serviceCharacteristic.setValue(reading); //reading value from load sensor is eg ; 89943

Then,on. the client side in my Swift app, once I figured out that the Arduino BLE Device was sending out FOUR bytes of data by calling data.count I changed the type from [UINIT8] to [UINT32] and BAM! now I just need to get the first value in the array!

Edit: I changed the [UInt32] Array to a native [Int] to achieve the same result.

If anyone sees an issue to the way I'm doing this or can make the code more explicit and efficient please yell out!

   guard let data = characteristic.value else{
            return
        }
        
        print(data.count)
        let numberOfBytes = data.count
        var rxByteArray = [Int](repeating: 0, count: numberOfBytes)
          (data as NSData).getBytes(&rxByteArray, length: numberOfBytes)
          print(rxByteArray)

  • Related