Detect power switch from USB to Vin


I'm new to arduino development and just needed a little help. I want to power the arduino uno(rev 3) using usb. As soon as the usb is removed ,i want the arduino to detect the change and power through a battery pack(9v). The 9v Vin will be initially plugged in with the usb but somehow i want the preference to be the usb power.
The idea is basically to build a laptop security device. if someone plugs out the arduino from the laptop, an sms gets sent to a preset number. The arduino will be powered through the Vin during this period. So there has to be a way to detect a change so i can send the appropriate AT commands to the sms module only when usb power is diconnected.
Thanks in advance..

Fundamentally that is not the way the arduino is designed, if you want to do this then you will have to build your own board with the power switching logic like you want.

Could you design the battery source to provide a voltage below the nominal 5V on the USB, so that the USB is used in preference? You may need to reduce the clock frequency to get reliable operation at the lower voltage. If that works, then your next challenge is to work out whether the '5V line' is above the battery voltage or not. I would have thought a voltage divider and analog input would tell you that.

Solder a wire between the usb power on the back of the arduino to a digital input and simply read the io.
When the usb is powered down, the io should read low and when plugued in the laptop, the io should read high.

Solder a wire between the usb power on the back of the arduino to a digital input and simply read the io.

No that doesn't work, I have just checked it. The USB gets back power from the supply so the pin is always high.

Why can't you separate the two and use a diode to prevent the power feed back.

Because of e forward volts drop it introduces.

For the USB pin always high, it seems to depend on your board. On my UNO it is not always high but on a Chinese replica(ex:DKUno) it is always high.

How're your rework skills?
Look at the top left of the schematic, U5A.
This is the comparator that switches Transistor T1 to allow the USB supply thru when Vin/2 is lower than 3.3V.
So do this - lift pins 2 and 3, wire pin 3 to 3.3 and wire pin 2 to RN1 pin 1 or 2.

Arduino_Uno_Rev3-schematic.pdf (95 KB)