#include <EEPROM.h>
/***
Write a program that puts the value of a temperature sensor into the eeprom every 100 ms.
THere is a switch.
When the switch is to the left, the uno records temperatures
When the switch is to the right, the uno reads back temperatures
and prints to the serial monitor, starting with the newest temperature
***/
//#include <EEPROM.h>
/** the current address in the EEPROM (i.e. which byte we're going to write to next) **/
int address = 0;
int stop_recording = 0;
// there's a limit to the size of the eeprom, we'll handle that
// by just not recording new temperatures when the eeprom
// memory is full. This variable is used to keep track of that.
void setup() {
Serial.begin(9600);
Serial.println("start");
}
void loop() {
int switch_position = digitalRead(8);
if (switch_position == LOW) {
/***
Assume an analog temperature thermistor is attached to A0
Don't be concerned with turning into a temperature, it's just data
Analog read returns a value between 0 and 1023 but each
eeprom cell only holds a value between 0 and 255. 1023 won't fit
So we need to divide the value into two parts, a high and a
low. So 1023 is 2^10.
Divide the val from analogRead by 256 into an integer. That
will give up an upper part. For the lower part do val % 256.
Try it:
Say val is 938. 938/256 = 3
The result of 938 % 256 = 170
The formula for putting it back together is:
(3*256)+170 = 938
0 to 1023 and each byte of the EEPROM can only hold a
value from 0 to 255.
***/
int val = analogRead(0) / 4;
int lo;
int hi;
//convert val into the lo and hi variables
lo = 0x00FF & val;
hi = val >> 8;
//val is 0b000000111000101
//lo gets 10010101
//hi gets 00000011
Serial.print("address = "); Serial.println(address);
//use EEPROM.write(address, val) command to store into two consecutive locations
EEPROM.write(address, lo);
address++;
EEPROM.write(address, hi);
address++;
//update the address variable as needed
if (address > EEPROM.length()-2) {
stop_recording = 1;
} else {
stop_recording = 0;
}
//wait 100 ms for the next record
} else {
//switch is to the right, go backwards through the eeprom memory
//read the "lo" value
//**************************
//Add code below to finish the task of printing out the eeprom data
int lo = EEPROM.read(address);
address--;
int convertedValue = 0;
EEPROM.write(EEPROM.read(address) - 1, address);//decrement the address
//read the hi value
EEPROM.write(EEPROM.read(address) - 1, address);//decrement the address
convertedValue = map(address, 0, 1023, 0, 255);//reassemble into a 0 to 1023 value
//print the value
Serial.print("temp voltage =");
Serial.println(address);
Serial.print("Converted EEPROM Value = ");
Serial.println(convertedValue);
delay(100);
}
}