Serial Port ReadLine vs ReadExisting or how to read the data from serial port properly

折月煮酒 提交于 2019-11-28 09:11:06

I have never had luck with ReadLine working. Just do a Read into a local buffer whenever data is available and then use a separate thread to scan the data and find line breaks yourself.

Depends on what the end-of-line (EOL) character(s) is for your input data. If your data is line oriented then ReadLine is a valid function to use, but you may want to look at the NewLine property and be sure that it is set appropriately for your input data.

For example, if your scale outputs linefeed for EOL then set port.NewLine = "\n";

http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.newline.aspx

I would like to comment to Elias Santos but I dont have enough reputation. There are some gotchas in using the ReadExisting method:

https://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readexisting(v=vs.110).aspx

Note that this method can leave trailing lead bytes in the internal buffer, which makes the BytesToRead value greater than zero.

I faced some issues with ReadExisting before and this is because of the unwanted bytes. Using Readline fixed those issues.

if (serialPort1->IsOpen){
    if (serialPort1->BytesToRead>0){
        this->textBox1->Text += serialPort1->ReadExisting();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!