I'm getting lots of invalid unicode characters from my serial reading and changing the Encoding helped but didn't solved the issue. The message should be "Hello World!0x0D" and half of the time I get "Hello World!" just fine but the other half I get weird unicode characters, like the image below.
I'm using a Industrial controller (PLC) to send the ASCII code: 48h 65h 6Ch 6Ch 6Fh 20h 57h 6Fh 72h 6Ch 64h 21h 0Dh with byte order Most significant bytes first. The ASCII code stands for "Hello World!(CR)" where (CR) means Carriage return If you count the number of invalid chars you will notice that is the same amount of the actual message... Looks like somehow my computer can't understand the messages half of the times.
I tried change the Encoding to BigEndianUnicode, UTF-8, UTF-32, Unicode, ASCII and GetEncoding("Windows-1252"); but it didn't worked. Either I get "\0" before every char or invalid unicode characters half of the time. Could someone shed a light on this matter?
The serial port constructor:
_serialPort = new SerialPort(cbPort.Text);
_serialPort.BaudRate = Int32.Parse(cbBaudrate.SelectedItem.ToString());
_serialPort.Parity = Parity.None;
_serialPort.StopBits = StopBits.One;
_serialPort.DataBits = 8;
_serialPort.ReadTimeout = 500;
_serialPort.Encoding = System.Text.Encoding.BigEndianUnicode;
_serialPort.Open();
The ReadSerial Event:
private void ReadSerialEvent(object sender, SerialDataReceivedEventArgs er)
{
try
{
while (_serialPort.BytesToRead > 0)
{
read = (char)_serialPort.ReadChar();
switch (read)
{
case '\r':
break;
case '\u0d00':
ShowSerialData(message);
message = "";
break;
default:
message += read;
break;
}
}
}