I have an arduino mega that i am using as a clock. I would like it to detect if it is connected to a USB or external power supply (e.g. a battery). I then want to set a variable to different values depending on the result, so i can display it on an OLED.


Use a simple transistor where the Vin (external power) is connected to the base, which switches the transistor. Than connect the collector to +5V, and the emitter to a GPIO input pin and read the status with the Arduino. If it receives a HIGH you know external power (via Vin) is used.

See the useful 'good' answer as comment of Majenko below ... I will leave the answer above as is, to keep his remarks clear.

  • 2
    Slightly more involved than that - you want to have the transistor (NPN or N-channel FET) between the GPIO and Ground, not +5V, and a pullup resistor (or enable the internal pullup resistor of the GPIO pin) and look to see if it's reading LOW for "External Power Applied". Also a resistor in the base of an NPN is needed.
    – Majenko
    Sep 19 '17 at 9:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.