flutter_blue
flutter_blue copied to clipboard
Issue when reading and writing REAL numbers
So I've been working with Arduino Nano 33 BLE Sense and I'm using the ArduinoBLE library . I know that I can send an encoded string and parse it to my board, but I want to make it memory efficient and only send real numbers.
WRITE = flutter_blue; READ = ArduinoBLE
In my dart code, I have:
await my_characteristic?.write([1000]);
In my arduino board, I have:
BLECharacteristic my_characteristic(MY_UUID, BLERead | BLEWrite, sizeof(uint32_t));
uint32_t value = 0;
my_characteristic.readValue(value); // this will immediately store my value
After reading, value = 232
😕😕😕
I just noticed that it is sending a type of byte array to my board. So I have to convert my data before sending. P.S. I know the Endianness of my board after doing some test.
Uint8List integerToBytes(int value) {
return Uint8List(4)..buffer.asByteData().setInt32(0, value, Endian.little);
}
var data = integerToBytes(1000); // [232, 3, 0, 0]
await my_characteristic?.write(data); // Success! this is the real value that I want to send.
WRITE = ArduinoBLE ; READ = flutter_blue
Now the board is the sender:
my_characteristic.writeValue(1000);
Then I am reading the same byte array in my dart code, So I have to convert it vice versa:
num bytesToInteger(List<int> bytes) {
/// Given
/// 232 3 0 0
/// Endian.little representation:
/// To binary
/// 00000000 00000000 00000011 11101000
/// Combine
/// 00000000000000000000001111101000
/// Equivalent : 1000
num value = 0;
if (Endian.host == Endian.big) {
bytes = List.from(bytes.reversed); //Forcing to be Endian.little (I think most of the devices nowadays uses this type)
}
for (var i = 0, length = bytes.length; i < length; i++) {
value += bytes[i] * pow(256, i);
}
return value;
}
var readValueArray = await my_characteristic?.read(); // [232, 3, 0, 0]
num readValue = bytesToInteger(readValueArray!); // 1000. Successful reading!
That is how I solved my problem. I hope there is a new version of flutter_blue to read and write real numbers based on this issue.
I just started using this package. Please let me know if I miss something.
This is not something flutter blue will ever do, nor any other bluetooth library. Its up to the developer to unpack data and know the format of the data.