在C#中从串行端口读取字符 [英] Read characters from serial port in c#

查看:75
本文介绍了在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()方法会在 some 个字节可用时立即返回,如果人为地使程序变慢,则驱动程序只有足够的时间才能接收所有10个字节,因此只有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);
}

另一种常见的解决方案是发送一个唯一的字符以指示数据的结尾.换行符('\ n')是一个很好的选择.现在,它变得更加简单:

Another common solution is to send a unique character to indicate the end of the data. A line feed ('\n') 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#中从串行端口读取字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆