简体   繁体   中英

Read characters from serial port in c#

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 ??

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM