I had project to save data to arduino EEPROM for counting motor rotation
and I had succed it
but the problem is when blackout happen the data would be lost
so
I try to write data into EEPROM and read it
it was succed
but the problem is the data has been looping around and it wont go further
#include <EEPROM.h>
int sensorValue;
int sensorPin = 2;
int ledPin = 0;
long kwhrp=0;
int add=0;
void setup()
{
Serial.begin(9600);
// initialize the sensor pin as an input:
pinMode(sensorPin, INPUT);
}
void loop()
{
sensorValue = digitalRead(sensorPin); // read the value from the sensor
Serial.println(sensorValue);
if (sensorValue == LOW)
{
ledPin = ledPin + 1;
kwhrp = ledPin * 455;
Serial.println(ledPin);
Serial.println(kwhrp);
Serial.println();
EEPROM.write(ledPin, add);
delay(700);
}
ledPin = EEPROM.read(add);
Serial.println(ledPin);
Serial.println();
}
the second problem is when " kwhrp " get value by 32500
it will decrement automatically
any feedback, suggestion, and comment is appriciate and please tell me where did I go wrong.....
The name ledPin implies that it stores the number of the pin that an LED is attached to. That hardly seems to be consistent with how you are using it. So, clearly that variable needs a better name.
EEPROM.write(ledPin, add);
The first argument is address. The second is the value to write. The function ONLY writes bytes. This code is writing 0 to a new location every time through loop when the sensor value is LOW. Hardly seems a useful thing to do.
The sensor value may be LOW for many iterations of loop.
Since ledPin and 455 are both ints, the result of the multiplication will be an int. It doesn't matter that the variable to store the value in can hold something larger than an int. You could multiply by 455L, which would force the result of the multiplication to be a long, rather than an int.
As PaulS said the first argument is the EEPROM address and the second is the value stored.
In this line: EEPROM.write(ledPin, add); You are storing the value of add which is always 0 in the EEPROM address of the current ledPin.
Example: your LED was ON on pin 3, that line above stores the add value of 0 in EEPROM address 3.
This line: ledPin = EEPROM.read(add); Is correct in that it is reading address 0 of the EEPROM but there is no value stored there.
So this:
EEPROM.write(ledPin, add);
needs to be changed to this:
EEPROM.write(add, ledPin);
You have no code in there to turn the selected LED on or back on after power failure.