开发者

Read Serial Reply After Write With C#

开发者 https://www.devze.com 2023-02-21 10:30 出处:网络
Is it possible to read the reply from a serial port right after sending a command in C#?I have a stepper motor driver and am trying to read the current step number and display it in the status bar of

Is it possible to read the reply from a serial port right after sending a command in C#? I have a stepper motor driver and am trying to read the current step number and display it in the status bar of my C# Windows form program with the .net framework 4.0. To do this I need to send the "RC" command. The driver then sends back the number. My question is this: How do you read the serial reply immediately after writing to the serial port? Any help 开发者_如何学Gowith this would be very helpful!


Yes, call ReadLine().

There's an issue however, serial ports are glacially slow. A common baudrate setting is 9600 baud, each character takes one millisecond to get received. Say you get 6 digits back, you're looking at RC + lf + 000000 + lf + controller overhead milliseconds. Your program is dead to the world for at least 10 milliseconds. The equivalent of about 20 million cpu cycles.

Whether that's a real problem entirely depends on how many cpu cycles you need in your app. You solve it by using threading, either explicitly with a thread that does nothing but talking to the controller or by using the DataReceived event.


You will probably want to use the ReadExisting Method which includes a combo of stream and buffer. Without knowing specifics I highly recommend checking MSDN docs here

SerialPort Class (System.IO.Ports)

0

精彩评论

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