Change SerialPort's BaudRate while connection is open

廉价感情. 提交于 2019-12-24 00:58:07

问题


I am using SerialPort class to communicate with an external device. I start the communication at 300 Baud per second however after the initial "handshake" I have to switch to a Baud rate specified by the device (usually 9600 Bps).

I have been unsuccessful in my attempts to continue communicating after I increase Baud rate however I am not sure why. That leads me to my question: What is the proper way of changing the Baud rate? Can it be done while the connection is open, or should I close the connection first?

I have been unable to find any information about this in the documentation...

I have tried both and have been unsuccessful in both ways, which made me think that I must be missing something obvious.


回答1:


From my experience so far, the safest bet is to close the connection first, change the rate, and then open it again. Your device won't mind this, as it probably waits for you to send some control characters to make sure the speed has been changed.

You can try changing the baud rate while the port is open, but this may result in invalid characters being detected in the buffer (depending on the device and the protocol), which means you should also clear the buffers immediately after the change (using SerialPort.DiscardInBuffer()).




回答2:


It turns out you can change SerialPort.BaudRate while it is open. But the SerialPort.DiscardInBuffer that is mentioned in answer by @Groo is a good tip!



来源:https://stackoverflow.com/questions/8852611/changing-the-speed-on-an-open-serial-port

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!