0

I am using this windows library: System.IO.ports I have a class called ServerObject and it has a public member: sPort of type SerialPort.

ServerObject.sPort.PortName = "COM4"; 
ServerObject.sPort.BaudRate = 460800;
ServerObject.sPort.Parity = 0;
ServerObject.sPort.DataBits = 8;

ServerObject.sPort.Open();
ServerObject.sPort.DataReceived += new SerialDataReceivedEventHandler(ServerObject.sPort_DataReceived);

The above code runs once in the main. I am thinking that the last line here is the culprit.

The below code is the public method for the ServerObject class that that last line is calling.

public void sPort_DataReceived(object sender, SerialDataReceivedEventArgs e) //event for data appearing on the serial port.
    {
        try
        {
            string payload = null;
            payload = sPort.ReadLine(); //extract incoming message

            this.DebugMessageQueue.Enqueue(payload); 
        }

        catch (Exception ex)
        {
        }
    }

Whenever something gets onto that queue, it gets printed. I tested that. However, nothing is happening. Any ideas? I think that I am not understanding this event handler. Is it suppose to be in a loop? I thought that the event handler would call sPort_DataRecieved whenever data appears on the port. Does it only run once?

Evan L
  • 37
  • 1
  • 12

1 Answers1

0

From MSDN https://msdn.microsoft.com/de-de/library/system.io.ports.serialport.datareceived(v=vs.110).aspx:

The DataReceived event is not guaranteed to be raised for every byte received. Use the BytesToRead property to determine how much data is left to be read in the buffer.

Obviously your code will not work as expected due to this limitation. I suggest using a polling routine instead, which cyclically checks the input buffer.

Also, I suggest you test your serial connection in a simple and reliable way first. Avoid complicated elements like events. Send/receive data by writing into and reading from the buffer. Use a local terminal program (like HW Group Hercules, which can also be used for TCP client/Server and UDP) to exchange data with your application...

Tobias Knauss
  • 3,361
  • 1
  • 21
  • 45