AlexMacabu
AlexMacabu

Reputation: 137

Serial Messages Issue

I'm receiving in my serial port the message "Hello World!CRLF" (no quotes) at every 1 second, and I'm using ReadExisting() to read the message, but I can't understand why I'm receiving lots of "\0" before every character.

Visual Studio Debug

PuTTy seems to handle the messages just fine, so my code must be the problem. Could someone please help me to figure this out?

PuTTY

Part of my code:

void button1_Click(object sender, EventArgs e)
    {
        try
        {
            _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.Open();
            if (_serialPort.IsOpen)
            {
                try
                {
                    ReadSerialData();
                }
                catch (TimeoutException) { }
            }

        }
        catch (Exception er){}

    }
    private void ReadSerialData()
    {
        try
        {
            ReadSerialDataThread = new Thread(ReadSerial);
            ReadSerialDataThread.Start();
        }
        catch (Exception e){}
    }

    private void ReadSerial()
    {
        try
        {
            while (_serialPort.BytesToRead >= 0)
            {
                readserialvalue = _serialPort.ReadExisting();
                ShowSerialData(readserialvalue);
                Thread.Sleep(1);
            }
        }
        catch (Exception e){}
    }


    public delegate void ShowSerialDatadelegate(string r);

    private void ShowSerialData(string s)
    {
        if (rtb_msg.InvokeRequired)
        {
            ShowSerialDatadelegate SSDD = ShowSerialData;
            Invoke(SSDD, s);
        }
        else
        {
            rtb_msg.AppendText(readserialvalue);
        }
    }

Upvotes: 0

Views: 95

Answers (2)

AlexMacabu
AlexMacabu

Reputation: 137

As sugested by @Hans Passant changing the encoding to BigEndian solved the main issue. Still getting lots of invalid unicode chars, but I think is best to open another thread. Thank you all for the support.

        _serialPort.Encoding = System.Text.Encoding.BigEndianUnicode;

Upvotes: 1

Nicholas E
Nicholas E

Reputation: 414

Are you sure that you want to read from the serial port even if there are 0 bytes to be read? If not, you might want to try changing: while (_serialPort.BytesToRead >= 0) to while (_serialPort.BytesToRead > 0) I suspect you may be reading from the serial port with 0 bytes to be read, which could return a null (\0) value

Upvotes: 0

Related Questions