如果您不想将所有代码放在using
块中,则可以在最后显式关闭端口。
SerialPort port = new SerialPort();
port.PortName = "COM16";
port.BaudRate = 38400; // Baud rate = bits per second
port.DataBits = 8; // unnecessary as 8 is the default
port.Parity = Parity.Even; // unnecessary as Even is the default
port.StopBits = StopBits.One; // unnecessary as One is the default
如果仍然无法连接,请尝试使用Termite进行连接,这是一个串口终端程序。如果您必须选择“DTR/DTS”之类的设置才能使其工作,那么您可能需要这样的设置:
port.DtrEnable = true;
port.RtsEnable = true;
然后打开你的端口。
port.Open();
port.DataReceived += OnRx; // Add the event handler for receiving data
异步读取的最简单方法是创建一个事件处理程序并将数据传递回该方法可以访问的变量。
List<string> rx = new List<string>(); // the event handler stores the received data here
// Add this method to your class to read asynchronously.
protected void OnRx(object sender, SerialDataReceivedEventArgs e) {
while (port.BytesToRead > 0) {
try {
rx.Add(port.ReadLine());
} catch (Exception) { }
}
}
关闭你的端口
port.Close();
另请查看SerialPort
文档。