I'm using this way for reading from serial port :
public static void Main()
{
SerialPort mySerialPort = new SerialPort("COM1");
mySerialPort.BaudRate = 9600;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
mySerialPort.Open();
Console.WriteLine("Press any key to continue...");
Console.WriteLine();
Console.ReadKey();
mySerialPort.Close();
}
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
Debug.Print("Data Received:");
Debug.Print(indata);
}
as we know This kind of API is called the Event-based Asynchronous Pattern (EAP), I want to write above code using Async Await method.
PS : with above code sometime I'm getting wrong data
Thanks in Advance
You can also read data from SerialPort.BaseStream. Which is of type Stream so supports the awaitable ReadAsync() method. Converting it to a string is up to you, use the proper Encoding. The default for SerialPort is ASCIIEncoding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With