I'm trying to read data from COM port, but I'm stuck with this issue so long. We're having some USB serial port device which is running on COM4 port, with that we have some predefined commands to execute and also there are some predefined outputs.
Our requirements is to send command to the COM4 port and read result.
Here what I have tried:
class Program
{
[STAThread]
static void Main(string[] args)
{
string cmd = "PING";
SerialPort mySerialPort = new SerialPort("COM4");
mySerialPort.BaudRate = 115200;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.DtrEnable = true;
mySerialPort.RtsEnable = true;
mySerialPort.Open();
mySerialPort.Write(cmd);
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
Console.WriteLine(mySerialPort.ReadChar());
Console.WriteLine("Press any key to continue...");
Console.WriteLine();
Console.ReadKey();
mySerialPort.Close();
}
}
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string data = sp.ReadExisting();
Console.WriteLine(data);
}
But It's stuck with black console screen, even DataReceivedHandler
is not called, and not able to get anything from COM4 port.
I've gone through many similar topics:
.NET SerialPort DataReceived event not firing
How to Read and Write from the Serial Port
And many mores, but no luck so far.
Am I missing something here?
P.S: It's working with RealTerm application, where we pass same command and are able to get output