1

I found this post which asks a similar question. However, the answers were not what I expected to find so I'm going to try asking it a little differently.

Let's assume a function searching_for_connection will run indefinitely in a while True loop. It that function, we'll loop and preform a check to see if a new connection has been made with /dev/ttyAMA0. If that connection exists, exit the loop, finish searching_for_connection, and begin some other processes. Is this possible to do and how would I go about doing that?

My current approach is sending a carriage return and checking for a response. My problem is that this method has been pretty spotty and hasn't yielded consistent results for me. Sometimes this method works and sometimes it will just stop working

def serial_device_connected(serial_device: "serial.Serial") -> bool:
    try:
        serial_device.write(b"\r")
        return bool(serial_device.readlines())
    except serial.SerialException
        return False
  • Is the device expected to reliably respond when you send it a carriage return? – Robert Harvey Feb 04 '21 at 16:26
  • Yeah the device that I'm connecting to should be sending responses to carriage returns – Justanothermatt Feb 04 '21 at 16:27
  • 1
    You may have to wait for a defined period to allow for the inevitable latencies. – quamrana Feb 04 '21 at 16:28
  • That's something I hadn't thought of. Any recommendations for a sleep period? – Justanothermatt Feb 04 '21 at 16:30
  • Well you have to allow for your `b"\r"` single character to make it through the driver software and over the line. (btw what is your baud rate?). Then you have to allow for the device to generate a response (this is the difficult one) and then allow for the response. (so what is the response? is it another `b"\r"` or more?) – quamrana Feb 04 '21 at 16:33
  • Baud is either 9600 or 115200 depending on some other factors. Response should just be `b"\r"` as far as I'm aware – Justanothermatt Feb 04 '21 at 16:36
  • So, for 9600 baud, you need to delay `1.04ms` for each `cr`, so `2.08ms`, plus the internal latency of your device. It may be a suck-it-and-see, but you could try a fixed `time.sleep(0.01)` after the `.write()` and before the `.readlines()`. – quamrana Feb 04 '21 at 16:39
  • Between that and a reboot of both devices it seems to be working. Throw an answer below and I'll accept it. Thanks for the help! – Justanothermatt Feb 04 '21 at 16:45

1 Answers1

1

I suggest having a delay to allow time for the device to respond.

import time

def serial_device_connected(serial_device: "serial.Serial") -> bool:
    try:
        serial_device.write(b"\r")
        time.sleep(0.01)
        return bool(serial_device.readlines())
    except serial.SerialException
        return False
quamrana
  • 37,849
  • 12
  • 53
  • 71