开发者

SerialPort - Clear Existing Data

I'm using the .NET SerialPort class to communicate with gauges. Every time a button on a gauge is pressed a reading value is sent over port.

The problem I have is that if the gauge button is pressed while the program is off then when the program starts it fires the data received event for that existing data. I don't want this behavior -- I only want to collect readings done after the port is opened.

I have a current workaround using a Thread.Sleep but it seems hacky and I'm wondering if anyone knows of a better solution.

port = 开发者_如何学JAVANew SerialPort("COM1", 9600, Parity.None, 8, StopBits.One)

port.Open()
port.DtrEnable = True

System.Threading.Thread.Sleep(100)
port.ReadExisting()

AddHandler port.DataReceived, AddressOf PortDataReceived

If I don't have the Thread.Sleep then the DataReceived event is fired for the previous gauge data. I'm guessing this is because the ReadExisting doesn't block and so when its called immediately after an open it just reads nothing.

Thanks


So if you call 'port.BytesToRead()' immediately after open its zero. If you call it 100ms after open its non-zero. I guess this makes sense -- it takes time after open to read the existing data.

Another option is to call read and set the read timeout but that seems no different than Thread.Sleep except you have to catch an exception...


 port.DtrEnable = True

That could have a side-effect. The gauge might be jumping up and down, eager to send the reading. After all, somebody pressed the button to tell it that it's okay to send. But its transmit routine is observing the handshake protocol, Data Terminal Ready is not on. Jump, jump, ah! it's on. Send. That takes a while, depends on the baudrate.

Well, why did somebody press the button even though the computer wasn't ready? Why isn't it always ready? Answer that question, then you can delete Sleep(). Also find out what happens when that somebody presses the button a hundred times before the computer is ready. Your Sleep() might well be too short.


If you don't need to collect what is waiting in the out buffer of the serialport try calling the serialPort.DiscardWriteBuffer() serialPort.DiscardOutBuffer() which should clear out whatever has collected there. Thanks to Chad for correcting my error.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜