When Arduino is powered by external source using Vin PIN do something
When is connected by USB power do something else.
The issue is how to understand which power source is actually connected.
Reading this schematic : http://arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf I think the best way is to connect USBVCC pin directly (or passing through a diode) to a digital pin, for example pin 7.
So, reading the digital state of this pin I can understand what kind of power source is providing energy.
I would not burn my precious Arduino UNO board!! That's why I'm asking you guys before proceed.
fsuperga:
The issue is how to understand which power source is actually connected.
Reading this schematic : http://arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf I think the best way is to connect USBVCC pin directly (or passing through a diode) to a digital pin, for example pin 7.
So, reading the digital state of this pin I can understand what kind of power source is providing energy.
Yes, you can do that. I suggest you use a series resistor of at least 10K between USBVCC and the pin, to protect the input pin in case the USB voltage is a little higher than the regulator voltage.
Definitely a resistor and not a diode - a reverse biased diode will allow the pin to 'float'. And make sure the internal pull-up is disabled on the pin in question.
I think just a resistor is not the right solution for this reason: USBVCC could be powered up by potential state of PIN7, so the current can flow from PIN7 to USBVCC. And the automatic power source selection's circuit could be stressed.
So I think the circuit could be:
USBVCC----------D|------------ PIN7
|
1MR
|
GND
Where:
D| is a diode
1MR is 1MOhm pull-down Resistor
GND is Ground
I can disable internal pull-up resistor with:
pinMode(pin, INPUT); // set pin to input
digitalWrite(pin, LOW); // turn off pullup resistors
fsuperga:
The pull-down resistor values must be 5,6Kohm
Yes, something 2k .. 20k is appropriate to pull down safely and only take a little current when VccUSB is active.
The diode is not really necessary, unless you switch pin7 both to OUTPUT and HIGH