Question

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 the serial port to a Python script and await a response. (via Serial.available()). It works well enough.

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

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top