flutter_libserialport
flutter_libserialport copied to clipboard
How to Read Data from Serial Port
well can someone tell me
how to read data to readable String ?
this is drop in replacement for https://pub.dev/packages/libserialport , so all examples there are valid.
You can do something like this:
import 'package:flutter_libserialport/flutter_libserialport.dart';
import 'dart:typed_data';
import 'dart:convert';
const availablePorts = SerialPort.availablePorts;
print(availablePorts.length);
//check here that your device exists
final port = SerialPort(availablePorts.last);
if (!port.isOpen && !port.openReadWrite()) {
print(SerialPort.lastError);
} else {
port.write(Uint8List.fromList("MY_COMMAND".codeUnits));
final reader = SerialPortReader(port);
reader.stream.listen((data) {
print('received: ${utf8.decode(data)}');
});
}
@tonyhart7 serial communication is low level communication. The protocol usually defined per device or accordingly some standard. Serial provides your array of bytes, than you should evaluate the bytes receive and convert them accordingly to the protocol you are implementing. As an example in order to read a string you need to know how the sender has encoded the string (let's say is encoded in ascii), you might also need to know which is the start byte and end byte (protocol usually uses STX and ETX bytes from ASCII table to which are respectively 0x02 and 0x03 in hex code), then from your side after you parsed the byte array and you have identified the bytes that are the string you want to read, you need to decode those byte using ascii.
More info on decoding/encoding can be found here https://api.flutter.dev/flutter/dart-convert/ascii-constant.html https://api.dart.dev/stable/3.3.0/dart-convert/dart-convert-library.html