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);
}
我们知道,这种API被称为基于事件的异步模式(EAP)使用Async Await方法编写上面的代码。
PS:有时在上面的代码下我得到了错误的数据感谢Advance
评论
抱歉,所以不是“为我编写代码”网站。了解有关async-await的更多信息(我想您目前对此并不了解),然后尝试自己编写代码。如果不起作用,请回到这里并提出问题。