USB or external power 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.