Works fine powered from USB works bad powered externally

OK. Thanks. It is then simply to detect the presence of mains voltage via an opto-coupler.
Then post the code you are using.