Read characters from serial port in c#

左心房为你撑大大i 提交于 2021-02-16 14:16:08

问题


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.

Here is my code:

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();

When I run the code, a message box shows up and displays only the first character. "0" alone is displayed in the message box.

Where have i gone wrong ??


回答1:


What you are doing wrong is not paying attention to the return value of Read(). Which tells you how many bytes were read.

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.

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 ('\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.



来源:https://stackoverflow.com/questions/15556177/read-characters-from-serial-port-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!