Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading from micro-controller

I have a Arduino micro-controller . The micro-controller works(i have an app that shows me the the micro-controller 'spits' out data. The thing is that i have implemented some code ( from http://www.c-sharpcorner.com/uploadfile/eclipsed4utoo/serialportcommunication12082008111137am/serialportcommunication.aspx ) :

Here i initialize the SerialPort

_serialPort = new SerialPort("COM17", 19200, Parity.None, 8, StopBits.One);
_serialPort.Handshake = Handshake.None;
_serialPort.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
_serialPort.ReadTimeout = 1000;
_serialPort.WriteTimeout = 1000;
_serialPort.Open();

And here i have the listening handler :

void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    Thread.Sleep(1000);
    string data = _serialPort.ReadLine();
    this.BeginInvoke(new SetTextDeleg(si_DataReceived), new object[] { data });
}

But i get this error :The operation has timed out. at string data = _serialPort.ReadLine(); in the handler .

The COM port is COM17 and the port opens ( a led on the micro-controller shows it ). Any idea why the operation timed out ?

i.e. The program loaded into the micro-controller is set to 'shoot' data at 1 second.

like image 556
Alex Avatar asked Sep 13 '26 12:09

Alex


2 Answers

The source of the problem is likely on the other end of the wire. To let SerialPort.ReadLine() complete and not generate a time-out error you must transmit a line end character sequence. The value of SerialPort.NewLine, which defaults to the line feed control character ("\n"). If you transmit bytes instead of characters then you should use Read() instead.

You should also implement the ErrorReceived event so you can detect communication errors. The kind you'll get when the communication parameters do not match, like Baudrate, Parity, Databits and Stopbits.

like image 181
Hans Passant Avatar answered Sep 16 '26 01:09

Hans Passant


You can't assume that when the DataRcvd event handler fires that you have everything that was sent by the other end. You likely are receiving pieces i.e. the micro controller sends ABCDEFGHI(newlinechar) and the event handler fires with ABC in the buffer.

I agree that if the micro controller is not sending newline then it will never work.

like image 21
dbasnett Avatar answered Sep 16 '26 01:09

dbasnett



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!