Power source identification (battery or USB)

Hello everyone.
For the purpose of the project I'm building, I want to identify whether the power that reaches the Arduino comes from the battery (9v) or whether the controller is connected to the PC via USB.
How can I check this?

Thank you!

Using a DVM.

you mean DVM ?

Digital volt meter. Or DMM too, Digital Multi Meter.

Use Serial.begin(); if it returns a true You have USB, else battery is powering things.
Are You sure what happens if both USB and battery are connected?

Serial.begin() is a void function.

Correct! Serial. available(); should have followed it.

But if power is coming from a dumb 5V source into the USB connector, such as a USB charger or powerbank, the Serial function wouldn't detect anything.

Seems like the safest way is to feed a resistive divider from the Vin pin, and take a voltage reading on an analog pin. If the battery is present, it will be providing power to the circuit, and the voltage measured will be a divided down 9V. Otherwise Vin will be a divided down 5V or 4.7V or 0V, depending on the Ardiuno.

You're thinking of if (Serial) and that only works on boards with a native USB interface. On something like an UNO it will always give true no matter what.

Oops.

Thank you it worked !

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.