I wa using flutter bluetooth serial package to recieve data from a microcontroller. When i send integer values from the microcontroller, I get the values in this form: [64], [144, 22]] the last number in the list(22) is the actual number i sent. however, everytime i send any values i get these two values as well [64], [144,...]. The other thing is when I send a float value from the micro controller, i receive it as int and when I try to convert the data type to double, I get an error like this:
The argument type 'void Function(double)' can't be assigned to the parameter type 'void Function(Uint8List)?'.
The argument type 'double' can't be assigned to the parameter type 'List'.
below is the snippet of the code where the first error arise
List<List<double>> chunks = <List<double>>[];
_getBTConnection(){
BluetoothConnection.toAddress(widget.server.address).then((_connection){
connection = _connection;
isConnecting = false;
isDisconnecting = false;
setState(() {});
connection.input?.listen(_onDataReceived).onDone(() {
if(isDisconnecting){
print("Disconnecting locally");
}else{
print("Disconnecting remotely");
}
if(mounted){
setState(() {});
}
Navigator.of(context).pop();
});
}).catchError((error){
Navigator.of(context).pop();
});
}
And below is the snippet of the second error arising:
void _onDataReceived(double data){
if(data != null && data > 0){
chunks.add(data);
}
if (kDebugMode) {
print(" chunks: , $chunks " );
}
}
CodePudding user response:
If you have a sequence of 8 (8-bit) bytes in a Uint8List
, you can obtain a ByteBuffer
or ByteData
view of it to parse those bytes into a 64-bit double
.
For example:
import 'dart:typed_data';
void main() {
// Big-endian byte sequence for pi.
// See <https://en.wikipedia.org/wiki/Double-precision_floating-point_format>
var bytes =
Uint8List.fromList([0x40, 0x09, 0x21, 0xFB, 0x54, 0x44, 0x2D, 0x18]);
var doubleValue = bytes.buffer.asByteData().getFloat64(0);
print(doubleValue); // Prints: 3.141592653589793
}
CodePudding user response:
Try this code to convert Uint8List
to List<double>
List<List<double>> convertUint8ListToDoubleList(Uint8List uint8list) {
var bdata = ByteData.view(uint8list.buffer);
return [List.generate(
(uint8list.length / 8).round(), (index) => bdata.getFloat64(index * 8))];
}