Typically we use the with
context manager to open and close e.g. a serial connection.
TODO need to go deeper on the underlying code how they are closed
For example
But in the case where you want to later loop through the serial objects, like mine, we need to handle the connection ourselves. Digging through the adafruit GPS docs, and then the busio
docs, since the first argument to the .GPS
initializer is a uart
device as defined there, I found the correct way to close the serial connection is the .close()
method of the uart
instance, which in the case of adafruit_gps
is stored as _uart
.
From https://docs.circuitpython.org/projects/gps/en/latest/_modules/adafruit_gps.html#GPS
So the final code, to loop through various GPS devices on different serial ports, without having to open/close the connection every time is:
Resources
- https://docs.circuitpython.org/en/latest/shared-bindings/busio/index.html#busio.UART
- https://docs.circuitpython.org/en/latest/docs/design_guide.html#lifetime-and-contextmanagers
deinitializing the hardware using a with statement will ensure hardware isn’t enabled longer than needed.
Note - we could also use the deinit()
class of bus.io UART
but I found that it didn’t work