yohannist
yohannist

Reputation: 4204

Connect to a device through a serial port and send a command, but nothing is returned

I need to connect to a sensor through a serial port and read some data off it. I connect to it and send the command, but nothing is returned from the device, instead a Timeout exception is thrown. Similar questions here on stackoverflow use the OnDataReceived event, i tried that and it did not work. The parameters i used to initialize and the command i send work as expected on Putty.

-- what am i missing here

void Read()
{
        SerialPort serialPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);

        try
        {
            serialPort.Handshake = Handshake.XOnXOff;
            serialPort.Encoding = new ASCIIEncoding();
            serialPort.ReadTimeout = 1000;
            serialPort.WriteTimeout = 900;
            serialPort.Open();


            serialPort.WriteLine("TEMP");
            MessageBox.Show("Reading");
            MessageBox.Show(serialPort.ReadLine());
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
            serialPort.Close();
        }
}

Thank you

Upvotes: 0

Views: 2579

Answers (2)

Fernando
Fernando

Reputation: 102

I would suggest that the problem is with the encoding you're using. To check if that's the problem use a sniffer of your choice to see that the bytes transferred on your application are the same as on putty.

Only be sure that you're actually trying to read the bytes when using a sniffer because if you don't they won't be shown on the output.

If that doesn't show you anything you can try to change your ReadLine() method to ReadByte() to ensure that there's no problem with the reading type that you're using.

Serial port sniffers

  • http://www.serialmon.com/
  • virtual-serial-port.org/products/serialmonitor/?gclid=CInI2ZPL_bsCFaxr7Aod8S4A8w
  • www.hhdsoftware.com/device-monitoring-studio

Upvotes: 1

Hans Passant
Hans Passant

Reputation: 941635

   serialPort.Handshake = Handshake.XOnXOff;

Maybe that's correct, it is pretty unusual. But real devices almost always pay attention to the hardware handshake signals, in addition to an Xon/Xoff flow control protocol. The DTR (Data Terminal Ready) and RTS (Ready To Send) signals have to be turned on before the device is convinced that it is connected to a real computer. A program like Putty will always turn them on, your program does not.

Add these two required lines:

   serialPort.RtsEnable = true;
   serialPort.DtrEnable = true;

And ensure that the serialPort.NewLine property correctly matches the end-of-message character used by the device. Temporarily use ReadExisting() instead to avoid getting bitten by that detail, don't leave it that way.

Upvotes: 2

Related Questions