This is called in a loop multiple times. It works perfectly with the USB power source.
As soon as I disconnect it from the USB and connect it to a battery (9V, 7805 regulator, outputs about 4.1V while USB provides 4.5V), something strange happens:
My project works for 11 iterations, then sends some broken characters through the serial and crashes the Arduino. It freezes or just resets.
Changing the variable vin to 0 will make this error appear also with the USB power.
There is no crash if dataString isn't assigned or the function isn't called.
It should actually do more complex things but I figured that the error appears with just these lines.
Everything works as it should with USB power.
It also works - without the line that assignes the dataString - with battery power, and the entire project works for the first 11 values.
My setup:
ATmega328p on a breadboard, with Duemilanove firmware and USBasp programmer.
This project should read the battery voltage and periodically wirte it on an SD card and send it via Serial to a bluetooth device.
PaulS:
Or a low battery. 4.1 V is not enough for a 5V Arduino.
The problem was the USB programmer still being connected.
It drew current (150mA) back from the battery and powered the programmer and a USB hub
I could solve the power issue with a diode but now it is pulling reset down to GND when it is connected so I will need to disconnect it to use my project.
Edit: Solved with another diode
Or a low battery. 4.1 V is not enough for a 5V Arduino.
The default brown-out threshold is 2.7V so the processor is quite happy at 4.1V. With a 16MHz crystal it
isn't speced to work much below that but in practice they seem to work even at 3.3V.
But the main clue is "String" - don't use the String class unless you've read up about the space-leak
issues (I think there is at least one bug fix that may help, but basically I would avoid it entirely.
If a 5V regulator is putting out 4.1V then your 9V supply simply isn't up to it. A PP3 sized battery? That
certainly won't handle the worst-case SD card (they have high power requirements). Most PP3 batteries can barely
handle a lone Arduino board to be honest.