C# – How to write character string to serial port using SerialPort.Write(String)

asciic++serial-portstring

Im trying to write a string to the serial port using SerialPort.Write(String).
So far i try it like followed

I instantiate the serial port object in my constructor.
EDIT: Setting the port parameters solved the problem.

public CSerialPort()
{
    this._serialPort = new SerialPort("COM6",1200,Parity.None,8,StopBits.One);
    this._serialPort.DataReceived += OnSerialPortDataReceived;
}

I open the port:

public void OpenSerialPort()
{
    try
    {
        _logger.DebugFormat("Trying to open Serial Port: {0}", this._serialPort.PortName);
        this._serialPort.Open();
        this.PortIsOpen = true;
    }
    catch (UnauthorizedAccessException ex)
    {
        _logger.DebugFormat("Trying to open Serial Port: {0}", ex);
    }
    catch (ArgumentOutOfRangeException ex)
    {
        _logger.DebugFormat("Trying to open Serial Port: {0}", ex);
    }
    catch (ArgumentException ex)
    {
        _logger.DebugFormat("Trying to open Serial Port: {0}", ex);
    }
    catch (InvalidOperationException ex)
    {
        _logger.DebugFormat("Trying to open Serial Port: {0}", ex);
    }
}

And i try to send the content of a string via the serial port:

public void WriteToSerialPort(string writeBuffer)
{
    this._serialPort.Write(writeBuffer);
}

Where the content of the String is:

this._serialPort.WriteToSerialPort("ABC");

My problem is that on the receiving side (another PC with a serial port monitoring software) i dont receive the "ABC".
What i receive is "รพ" which is ASCII character code 254.

I tried to change the Encoding property to all available encodings, but that didn't help.

Can anybody tell me what i can do to send any character string to the serial port using the serial port class?
Did i miss or misunderstand anything?

Best Solution

Try using:

byte[] MyMessage = System.Text.Encoding.UTF8.getBytes(yourString);

MySerialPort.Write(MyMessage,0,MyMessage.Length);

you may also want to check your BAUD rate on both sides of the connection (these need to be the same).