tags:

views:

1255

answers:

3

I have an Arduino sending and receiving instructions with a python script via a serial port.

The Arduino takes a button state and when it is pushed it will send a message via serial to a python script and await a response. (via Serial.available()). Works well enough.

However if the python script has crashed for whatever reason (ideally it will run in the background, so cant be easily checked) the Arduino will wait forever and even on a script restart will we unavailable.

Is there a way for my Arduino to check if there is something listening on the serial port? (and alert me with flashing lights etc if not) or is this not how serial works? Worst case I guess I could use a timeout, although that is not ideal.

+6  A: 

You have a limited ability to detect if there is something listening on the other side by using the DSR/DTR pins.

When you open the serial port on the machine your scripts runs on, it should raise its DTR pin (or you should be able to convince it to do so: the documentation of the library you use to drive the COM port should tell you how).

Then, on your Arduino, you can check its DSR pin (assuming null-modem wiring with handshaking, where the PC DTR pin is wired to DSR+CD on the Arduino) at regular intervals, and handle the 'nobody connected' scenario in any way you see fit.

One problem with this approach is that your PC script may not close the serial port when it crashes/stops responding, leaving the DTR pin enabled as if everything is still OK. Also, your script may simply miss the message from the Arduino due to errors on the serial line.

For that reason, you should always implement a timeout in your receive routines: even if there is a party listening at the other end, there is no guarantee it has received your message (or that its response will reach you intact).

Re-sending the message at least once (assuming DSR is raised) if a timeout occurs makes your protocol more reliable.

mdb
cheers mate. As an interesting point, google picked your answer up 3 minutes after you posted it.
Hyposaurus
Jeff Atwood twitted that google is almost 50% of traffic to this site. (Dang can't find the tweet, my google foo isn't working today)
Luka Marinko
Hey thanks for the starting hint, but unfortunately I can't find more on that to get any further. Can you provide some example code how to get access to DSR pin for Arduino? Cheers!
RngTng
A: 

I agree with mdb that timeouts are necessary, but would also add that you might want to implement simple challenge/response system that periodically checks if anyone is listening. (I like ircd's Ping-Pong analogy).

Luka Marinko
A: 

The arduino doesn't use the DSR line or any other handshaking line so you can't do what you suggest.

Mike