Serial port data has invalid new string characters

I wrote an application that sends data to a COM port and receives the returned data.

Sending works fine, but receiving does not. New line characters in a multiline and read-only text field are incorrect.

Screenshot:

enter image description here

My admission code is:

void serialPort_DataReceived(object s, SerialDataReceivedEventArgs e) { byte[] data = new byte[_serialPort.BytesToRead]; _serialPort.Read(data, 0, data.Length); string str = System.Text.Encoding.UTF8.GetString(data); textBox3.Text = textBox3.Text + str; textBox3.SelectionStart = textBox3.TextLength; textBox3.ScrollToCaret(); } 

And before opening the port, I set the New Line property to \ r \ n:

 _serialPort.NewLine = "\r\n"; 

How to fix it?

+4
source share
3 answers

From the documentation :

Gets or sets the value used to interpret the end of the call. ReadLine and WriteLine methods.

The key is that it uses to interpret the end of the call, not to establish .

The NewLine property handles how the SerialPort object tries to interpret incoming data. It does not manipulate incoming data.

In other words, by setting the NewLine property to "\ r \ n", you tell it to look for "\ r \ n" and use this as the NewLine character.

The data coming into the serial port is what it is. You cannot change how someone else sends data. (If you haven't written this app either.) You can only tell SerialPort how to read the data correctly.

What you need to do is find out what the program sends you and install .NewLine for it. Most likely, it simply sends either "\ n" or just "\ r", so if you set the NewLIne property to match, your program will begin to correctly recognize the newline characters that will be sent to it.

A bit more information that can help in using the SerialPort.ReadLine Property

+4
source

Try the following:

 _serialPort.NewLine = Environment.NewLine; 
+1
source

Decision:

 textBox3.Text = textBox3.Text + str.Replace("\r", "\r\n"); 
+1
source

All Articles