Click here to Skip to main content
16,016,537 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
MIDL
SerialPort sp = new SerialPort("COM16", 115200, Parity.None, 8, StopBits.One);       
string prn;
sp.Handshake = Handshake.None;

sp.WriteTimeout = 3500;
sp.ReadTimeout = 4500;

sp.Open();
sp.WriteLine("AT+CREG?\r\n");
prn=sp.ReadLine();

richTextBox1.AppendText(prn);
sp.Close();



when i debug code at sp.ReadLine()

it Some time shows Error
>>>
An unhandled exception of type 'System.TimeoutException' occurred in System.dll
Additional information: The operation has timed out.


some time it shows
>>
AT+CREG?

at readline(); i have tried using all possible combination of \n\r
Posted

1 solution

What's so unusual? You call a blocking operation with timeout, but something from the other side of the serial cable don't send you anything. :-)

You can check up the buffer if it has data and don't read when there is no data, use System.IO.Ports.SerialPort.BytesToRead and use longer timeout, use System.IO.Ports.SerialPort.ReadTimeout.

See http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.aspx[^].

Now, as you're dealing with blocking calls, do you use a separate thread for this purpose? You should. Your best option is creating a separate thread which unconditionally reads everything and push data to other thread when something happen. Read operation is blocking, so you don't want to block you main thread.

For appropriate inter-thread communication read my short Tips/Tricks article Simple Blocking Queue for Thread Communication and Inter-thread Invocation[^].

To notify UI thread, you need to use the method Invoke or BeginInvoke of System.Windows.Threading.Dispatcher (for both Forms or WPF) or System.Windows.Forms.Control (Forms only).

You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke()[^],
Problem with Treeview Scanner And MD5[^].

See also my collection of links to my past answers on threading:
How to get a keydown event to operate on a different thread in vb.net[^],
Control events not firing after enable disable + multithreading[^].

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900