I'd like to make a device behave differently based on whether a USB cable is connected (ideally I'd even like to know whether there is a serial connection or just a power supply).
On devices with a PMU (like M5StickC) I currently read the USB voltage. But that seems weird, since I have to import and initialize a PMU (module) and it doesn't tell me if I'm just connected to a charger or to a computer which might want to establish a connection.
Background: I want a bunch of different (ESP32 based) devices run some long-going routine (e.g. a UI) when they're "on their own" but fall back to REPL when it's connected to a PC (which is connected to me, who wants to program the device).
Is there a way to check if a USB cable connected to a ESP32 based device?
Re: Is there a way to check if a USB cable connected to a ESP32 based device?
The ESP32 itself knows nothing about USB, it's just a TTL UART provided by an external USB/UART chip. So it entirely depends on which board you're using as to whether the USB cable can be detected. Like you say, if there's a GPIO pin connected to the USB voltage then that's an easy option.
As to whether there's a PC at the other end, then you'd need a way to get that from the USB/UART chip (but just the UART connection won't be enough, you'd need something like a GPIO from an output on the USB/UART, if that exists).
Re: Is there a way to check if a USB cable connected to a ESP32 based device?
I'm pretty sure most USB/UART chips support (at least) RTS/CTS handshake. When these are wired to the ESP32, you might be able to find out if there is a PC attached or only a cheap power supply.
A few hours of debugging might save you from minutes of reading the documentation!
My repositories: https://github.com/karfas
My repositories: https://github.com/karfas
Re: Is there a way to check if a USB cable connected to a ESP32 based device?
Espressifs own devkits have this circuit where DTR and RTS on the USB to UART chip can control Reset and Io0 to enable automatic programming: So if that's what you are using you can send a signal to Io0 by manipulating DTR and RTS. But remember that a low on Io0 during power on will put it in firmware download mode.
If you are designing your own PCB you can ofcourse connect DTR and RTS to any pins you choose.