How to write a character string to serial port using SerialPort.Write (String)
I am trying to write a string to the serial port using SerialPort.Write (String). So far I have tried this as follows
I am instantiating a 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 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 am trying to send the content of a string through the serial port:
public void WriteToSerialPort(string writeBuffer)
{
this._serialPort.Write(writeBuffer);
}
Where is the content of the string:
this._serialPort.WriteToSerialPort("ABC");
My problem is that on the receiving side (another PC with serial port monitoring software) I am not getting "ABC". What I get is "þ" which is ASCII code 254.
I tried changing the Encoding property to all available encodings, but it didn't help.
Can anyone tell me what I can do to send any character string to the serial port using the serial port class? Am I missing or am I misunderstanding something?
+3
source to share