0

我在与串行设备通信时遇到问题。我无法确定波特率应该是什么。文档说信令速率为 38400 位/秒。

这是串行端口的文档。

文档

这如何转化为 .NETSerialPort类?

using (var port = new SerialPort("COM16"))
{
    port.BaudRate = 9800;       // ??
    port.Parity = Parity.Even;  // ??

    // anything else? anything wrong?

    port.Open(); //go!
}
4

1 回答 1

0

如果您不想将所有代码放在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 文档

于 2017-09-08T06:59:24.317 回答