使用 C# 写入后读取串行回复
在C#中发送命令后是否可以立即从串口读取回复?我有一个步进电机驱动器,正在尝试读取当前步数并将其显示在带有 .net Framework 4.0 的 C# Windows 窗体程序的状态栏中。为此,我需要发送“RC”命令。然后司机发回号码。我的问题是:写入串口后如何立即读取串口回复?对此的任何帮助都会非常有帮助!
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 with this would be very helpful!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,调用
ReadLine()
。然而有一个问题,串行端口非常慢。常见的波特率设置为 9600 波特,每个字符需要一毫秒才能接收。假设您返回 6 位数字,您正在查看 RC + lf + 000000 + lf + 控制器开销毫秒。你的程序至少有 10 毫秒的时间没有任何反应。相当于大约2000万个CPU周期。
这是否是一个真正的问题完全取决于您的应用程序需要多少个 CPU 周期。您可以通过使用线程来解决这个问题,可以显式地使用一个除了与控制器通信之外什么也不做的线程,或者使用 DataReceived 事件。
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.
您可能想要使用 ReadExisting 方法,其中包括流和缓冲区的组合。在不了解具体情况的情况下,我强烈建议您在此处查看 MSDN 文档
SerialPort 类 (系统.IO.端口)
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)