How to Make Arduino Know When It's Plugged In!
by NewsonsElectronics in Circuits > Arduino
590 Views, 8 Favorites, 0 Comments
How to Make Arduino Know When It's Plugged In!


After some fiddling around, I finally discovered how to detect when an Arduino is powered via USB — and the best part is that it doesn’t require any external hardware! 💡 The trick is to use the analog reference pin (AREF) and set it to EXTERNAL. By comparing the voltage on the AREF pin (which is tied to the 5V USB line when connected) against the internal reference, we can tell whether the Arduino is running on USB power or another source like a battery.
Supplies
1 Arduino
Some wires
External battery
The Circuit

First, Connect A0 to 5V rail
Second, Connect battery between GND and Vin
Third, Connect Vref to Vin Pin
Done!
The Code
// By Newson's Electronics
// Oct 15, 2025
// Detect if Arduino Uno is powered via USB or external (battery/VIN)
// and flash LED on pin 13 accordingly.
const int ledPin = 13; // Onboard LED pin
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
// Set analog reference to EXTERNAL
// AREF behaves differently depending on power source.
analogReference(EXTERNAL);
Serial.println("Power Source Detection Initialized...");
}
void loop() {
// Read analog reference difference (A0 can be unconnected)
long reading = analogRead(A0);
// Simple check: when powered by USB, A0 tends to saturate (1023)
// When on external/battery, it's lower due to voltage drop.
if (reading == 1023) {
Serial.println("🔌 Powered by USB");
flashLED(2, 100); // double flash for USB
} else {
Serial.println("Powered by Battery/External Supply");
flashLED(1, 300); // single slower flash for battery
}
Serial.print("Analog reading: ");
Serial.println(reading);
Serial.println("-------------------------");
delay(2000);
}
// Function to flash onboard LED
void flashLED(int times, int delayTime) {
for (int i = 0; i < times; i++) {
digitalWrite(ledPin, HIGH);
delay(delayTime);
digitalWrite(ledPin, LOW);
delay(delayTime);
}
}