c# - C#到微控制器的串行通信问题
问题描述
我在 Visual Studio C# 环境中与嵌入式设备进行串行通信时遇到问题,当前的解决方案是使用以下配置与腻子会话进行通信:
- 波特 > 9600
- 数据位 > 8
- 停止位 > 1
- 奇偶校验 > 无
- 流量控制 > RTS/CTS
每次建立连接时,腻子终端上都会显示一个菜单,其中显示控制器的可用命令。
我尝试了从 MS 示例中借用的以下内容:
public class PortChat
{
static bool _continue;
static SerialPort _serialPort;
public static void Main()
{
// Create a new SerialPort object with default settings.
_serialPort = new SerialPort();
_serialPort.PortName = "COM4";
_serialPort.BaudRate = 9600;
_serialPort.Parity = Parity.None;
_serialPort.DataBits = 8;
_serialPort.StopBits = StopBits.One;
_serialPort.Handshake = Handshake.RequestToSend;
// Set the read/write timeouts
_serialPort.ReadTimeout = 5000;
_serialPort.WriteTimeout = 5000;
_serialPort.Open();
Thread.Sleep(1000);
}
}
在“Port.Open”之后从端口读取会导致异常,请参见第一个屏幕截图。写入端口也会导致异常,请参见第二个屏幕截图。我在这里想念什么?
谢谢
解决方案
ReadLine 一直等到它看到 SerialPort.NewLine 字符串。如果这没有在 SerialPort.ReadTimeout 内到达,则会引发 TimeoutException。要么增加你的超时时间,要么使用ReadExisting()
.
根据 MSDN:[SerialPort.ReadTimeout] Gets or sets the number of milliseconds before a time-out occurs when a read operation does not finish.
By default, the ReadLine method will block until a line is received. If this behavior is undesirable, set the ReadTimeout property to any non-zero value to force the ReadLine method to throw a TimeoutException if a line is not available on the port.
推荐阅读
- java - MediaException:从导出的 JAR 文件运行项目时 MEDIA_UNAVAILABLE
- objective-c - 在调用函数之前检查类目标成员资格
- swift - 可编码错误 - 预计解码字典
但找到了一个数组 - mysql - 尽管已设置密码并在连接 uri 中输入密码,但用户 root@localhost 的 mysql 访问被拒绝(使用密码:否)
- html - 链接的线性渐变
- python - Pyautogui 键盘命令不适用于菜单栏分配
- google-maps - 如何在 Meteor 的子模板调用中传递空格键变量?
- python - 手动分析程序
- html - 为什么 mt-3 [mb-3] 没有应用于引导程序中的每一行?
- php - 在 PHP 中打印双精度值的真实值?