Code runs different when powered via USB and 9v

I have created a basic temperature guage which displays a range of leds depending on the ambient temp. If the temp is equal to or higher than the max then a fan comes on until the temp drops below the max. This works fine when my Arduino is powered through USB, however when the Arduino is powered by 9v battery the code runs ok until the fan comes on where it stays on, and on, and on, and on, etc instead of cutting out as it should.

Anyone know why this might be happening?

Can you post the code, please?

Generally given the same input a compiled program should behave every time exactly the same. So most probably you have different inputs and not some self modifying code. Different input most probably comes from the fact that you don't have stable voltage reference, but that can be discussed if you post some schematics.

And finally - sorry if I am making stupid observations and what I've mentioned you have had already checked and dismissed as a cause.

Note you will have slightly different voltages when working from external power and from USB. The external power is probably delivering (after the regulators) fairly close to 5.0V, so all of your A/D values are scaled from 0-1023 based on 0==>0V and 1023==>5V.

When operating from USB power, the specs are pretty loose. A USB bus can provide as little as 4.4V and still be within spec, and if you go through an unpowered USB hub you may lose even more. If now 1023==>4.4V then obviously this changes the thresholds of your software.

Try measuring the "+5V" voltage on your board in both cases to see if this is the issue.