0

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

Hina Khuman
  • 757
  • 3
  • 14
  • 41
  • Have you tried fiddleing with the `Handshake`? Maybe the other part need that set? – Frank Nielsen Dec 25 '17 at 12:23
  • 3
    My crystal ball says that you did *not* test this the same way with RealTerm. You would have to type PING and *not* press the Enter key. In all likelihood you have to send `"PING\n"` or use WriteLine() instead of Write(). Note the added \n, often necessary by the code on the other end of the wire to recognize the end of the command. It might be \r. If necessary change the SerialPort.NewLine property so WriteLine() can do the job. Similarly, you'd heavily favor ReadLine() in the DataReceived event handler so you get the entire response instead of just 1 or 2 characters. – Hans Passant Dec 25 '17 at 13:08
  • 1
    @HansPassant: Yes, `\r` works, thank you so much! – Hina Khuman Dec 25 '17 at 13:24
  • @HansPassant: Any thoughts [here](https://stackoverflow.com/q/48048213/5743676)? – Hina Khuman Jan 01 '18 at 10:38

0 Answers0