Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading from serial port asynchronously using Async await method

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

like image 687
Sirwan Afifi Avatar asked Dec 08 '22 12:12

Sirwan Afifi


1 Answers

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.

like image 93
Hans Passant Avatar answered Dec 12 '22 23:12

Hans Passant