Read characters from serial port in c#(从 C# 中的串口读取字符)
问题描述
您好,我正在使用 Read() 方法从串口读取 10 个字符,例如 0123456789.实际上字符是由PIC单片机发送的.
Hello I am using Read() method to read 10 characters say 0123456789 from serial port. Actually the characters are sent by a PIC Micro-controller.
这是我的代码:
serialPort1.PortName = "com4";
serialPort1.BaudRate = 9600;
serialPort1.Open();
char[] result = new char[10];
serialPort1.Read(result, 0, result.Length);
string s = new string(result);
MessageBox.Show(s);
serialPort1.Close();
当我运行代码时,会出现一个消息框并且只显示第一个字符.消息框中只显示0".
When I run the code, a message box shows up and displays only the first character. "0" alone is displayed in the message box.
我哪里出错了??
推荐答案
你做错的是没有注意Read()的返回值.它告诉你读取了多少字节.
What you are doing wrong is not paying attention to the return value of Read(). Which tells you how many bytes were read.
串行端口是非常慢的设备,在典型的波特率设置为 9600 时,传输一个字节需要一毫秒.对于现代处理器来说,这是一个巨大的时间,它可以轻松地在一毫秒内执行数百万条指令.Read() 方法会在 一些 字节可用时立即返回,如果您人为地使程序变慢,那么您只能获得全部 10 个字节,以便驱动程序有足够的时间来接收所有这些字节.
Serial ports are very slow devices, at a typical baudrate setting of 9600 it takes a millisecond to get one byte transferred. That's an enormous amount of time for a modern processor, it can easily execute several million instructions in a millisecond. The Read() method returns as soon as some bytes are available, you only get all 10 of them if you make your program artificially slow so the driver gets enough time to receive all of them.
一个简单的解决方法是继续调用 Read() 直到你把它们全部搞定:
A simple fix is to keep calling Read() until you got them all:
char[] result = new char[10];
for (int len = 0; len < result.Length; ) {
len += serialPort1.Read(result, len, result.Length - len);
}
另一种常见的解决方案是发送一个唯一字符来指示数据的结束.换行 (' ') 是一个很好的选择.现在它变得简单多了:
Another common solution is to send a unique character to indicate the end of the data. A line feed (' ') is a very good choice for that. Now it becomes much simpler:
string result = serialPort.ReadLine();
现在还支持任意响应长度.只需确保数据不包含换行符即可.
Which now also supports arbitrary response lengths. Just make sure that the data doesn't also contain a line feed.
这篇关于从 C# 中的串口读取字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 C# 中的串口读取字符
基础教程推荐
- 将 XML 转换为通用列表 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- c# Math.Sqrt 实现 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01