I am using UART(4) and the Adafruit USB to TTL Serial Cable.
in my Boot.py I have:
uart = pyb.UART(4,115200)
pyb.repl_uart(uart)
Is there a way (in code) to know if this UART is actually conected at the USB end to a pc?
I am not using the red wire of the serial cable to power the pyboard.
uart question
Re: uart question
It looks like you can read the GPIO pin even when the pin is configured for an alternate function.
The UART Rx line normally idles high, and when the uart is configured, we set a pull-up on the line so that the line stays high when nothing is connected.
You can change that to a pull-down, and then the line would go low when the Tx from your USB-to-serial converter is disconnected.
I wrote a sample of how you might do that (I used UART 6):
Note that rx.value() may return zero if the UART is receiving characters, so you need to do more than just a simple poll to figure out if the line is dosconnected. Something like remembering the time of the last read and then setup a timer to poll periodically. If you see a low and it's been some amount of time since the last character and the line stays low for several character times (depends on baud rate), then you could conclude that the UART was unplugged. You could setup an ExtInt or poll to see the line go high.
So not necessarily trivial, but I believe it could be done.
Now having the line go low will cause a framing error in the UART, and I'm not sure how long that condition persists, so you might run into some issues around that (like perhaps you need to clear the framing error bit once you detect that the line goes high). Just speculation on my part, but something to keep an eye out for.
The UART Rx line normally idles high, and when the uart is configured, we set a pull-up on the line so that the line stays high when nothing is connected.
You can change that to a pull-down, and then the line would go low when the Tx from your USB-to-serial converter is disconnected.
I wrote a sample of how you might do that (I used UART 6):
Code: Select all
import pyb
tx = pyb.Pin('Y1', pyb.Pin.IN)
rx = pyb.Pin('Y2', pyb.Pin.IN)
uart = pyb.UART(6, 115200)
# Re-initialize the Rx pin to have pull down instead of pull-up
rx.init(pyb.Pin.AF_PP, pull=pyb.Pin.PULL_DOWN, af=pyb.Pin.AF8_USART6)
# Print out the Tx and Rx pins - make sure we changed Rx to pull down
print('TX = ', tx)
print('RX = ', rx)
print('rx.value =', rx.value())
So not necessarily trivial, but I believe it could be done.
Now having the line go low will cause a framing error in the UART, and I'm not sure how long that condition persists, so you might run into some issues around that (like perhaps you need to clear the framing error bit once you detect that the line goes high). Just speculation on my part, but something to keep an eye out for.