Lynn Emery

Lynn Emery

  • NA
  • 4
  • 18.4k

Serial Port Timeout

May 26 2016 6:31 AM

Hi I have a serial port which I send data and receive data from.

I can happily send data to the serial port and can receive data from the serial port, however I can only receive data successfully during the first iteration of my code, on the second iteration I can receive data but I then receive a timeout error.

I am reading the data from the port by bytesread() rather than readline() due to the device connected to the com port. I think the reason why the port is timing out is because the data being sent doesn't tell the received handler that all data has been received, so stop looking for it, and therefore it just hangs in the received handler and times out. My other thinking is that there is an issue with the thread and it is not closing or I need a thread for each piece of data received.
 
Below is my code - the programme reaptidly runs through all of this code each time data is sent/received so it maybe that I am not clearing a variable etc .
 
I have been looking at this problem for days so I gladly welcome any ideas or suggestions.
 
Thank you for your time and help in advance. 
 

private void ComSetUp(string inputString)

{

OutputString = inputString;

InitializeComponent();

//button2.Enabled = false;

//button2.Visible = false;

sp.BaudRate = 9600;

sp.DataBits = 8;

sp.StopBits = System.IO.Ports.StopBits.One;

sp.Parity = System.IO.Ports.Parity.None;

sp.ReadTimeout = 7000;

InitizeCount++;

_continue = true;

if (sp.IsOpen ==false)

{

sp.PortName = "COM5";

sp.Open();// change this to COM3 egs visit

}

sp.NewLine = "\r";

sp.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serial_DataReceived);

 
 Thread.Sleep(100);

localStatus = "RequestSent";

t1 = new Thread(SendRequestData);

t1.IsBackground = true;

t1.Name = "SendRequestThread";

t1.Start();

 
 
 
 

private void serial_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)

{

try

{

byte[] buffer = new byte[sp.ReadBufferSize];

int bytesRead = sp.Read(buffer, 0, buffer.Length);

tString += Encoding.ASCII.GetString(buffer, 0, buffer.Length);

if (tString.IndexOf((char)_terminator) > -1)

{

string workingString = tString.Substring(0, tString.IndexOf((char)_terminator));

tString = tString.Substring(tString.IndexOf((char)_terminator));      


sp.DiscardOutBuffer();

sp.DiscardInBuffer();

tString = "";

ProcessSerialBuffer(workingString);

}


}

catch (Exception ex)

{

MessageBox.Show(ex.ToString());

}

}

 
 

Answers (1)