flutter_libserialport icon indicating copy to clipboard operation
flutter_libserialport copied to clipboard

How to Read Data from Serial Port

Open tonyhart7 opened this issue 3 years ago • 1 comments

well can someone tell me

how to read data to readable String ?

tonyhart7 avatar Feb 05 '22 12:02 tonyhart7

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)}');
  });
}

mugi-luffy avatar Mar 12 '22 17:03 mugi-luffy

@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

lucafabbri avatar Feb 21 '24 12:02 lucafabbri