retentive memory

I'm making a vending machine with those spiral dispensers. I need to keep track of how many items have been vended, even when the machine is switched off. So, I need to store an integer when the arduino is switched off - so its still there when its next switched on. This may well be a stupid question, I'm very inexperienced with C.

tim H

Store it in EEPROM.

http://arduino.cc/playground/Code/EEPROMWriteAnything

When the Arduino powers back on, how can you tell if there is a previous value stored or not? The very first time you run this, I'd want to setup a default value, and store that. How can you tell if you're running the first time, or if you can pull an old value out of memory?

Provide a way to "reset" the value at the user's discretion, in the code. For example, a button to save the configuration/counter, or a jumper that indicates that the configuration/counter should be initialized, or a command that your serial port routines can detect to trigger a reinitialization of the value.

The factory usually initializes everything to 0xFF or 0x00, so it's tempting to put a magic unlikely value into EEPROM that says "hey, I'm initialized already!" but it's far more robust to provide a user button. That's why even the tiniest of watch-battery toys will offer such a button on the back. :slight_smile:

Another way to look at it is to have a Power Fail flag in EEPROM. Each time the program starts the flag is set to true. Only a graceful shutdown (by means of a button, etc.) will set the flag to false. We use this technique in our Point of Sale application. It still requires a button or the like as halley suggested.