A製作了一款帶有Arduino MEGA的溫度傳感器。用戶可以使用按鈕更改變量int templimit
。這個變量的值被寫入EEPROM,所以在重新啓動後它將保持其最後的值。我的問題是,在每次重啓時,我都會縮短EEPROM的使用壽命。如何避免使用EEPROM而不是閃存?
我的問題:有沒有辦法避免從EEPROM讀取/更新並將變量存儲在其他內存上?
保存到EEPROM:
void save_to_eeprom(unsigned int address, float config) { // (address, value)
for (byte i = 0; i < sizeof(config); i++) { // size of config is 4
EEPROM.write(address + i, reinterpret_cast<byte*>(&config)[i]);
}
閱讀從EEPROM:
float read_from_eeprom(unsigned int address) { //(address)
float config;
for (byte i = 0; i < sizeof(config); i++) { // size of config is 4
reinterpret_cast<byte*>(&config)[i] = EEPROM.read(address + i);
}
return config;
}
這是重啓後如何templimit
將保持其最後的值,完整的代碼是:
#include <EEPROM.h>
// this constant won't change:
const int buttonPin = 8; // up
const int buttonPin1 = 3; // down
const int buttonPin2 = 2; // enter
// Variables will change:
int buttonPushCounter; // counter for the number of button presses
int buttonState;; // up
int buttonState1;; // down
int buttonState2;; // enter
int templimit = read_from_eeprom(20); // temperature limit for alarm
void setup() {
Serial.begin(9600);
Serial.println("Update temperature limit if not wait 10 sec for time out");
updatevalue();
Serial.println("Done");
Serial.println(templimit); // temperature limit for alarm
}
void loop() {
// do nothing
}
int updatevalue(void) {
int timenow;
int timepassed;
int counter = 10;
timenow = millis();
while (buttonState == LOW and buttonState1 == LOW and buttonState2 == LOW) { // this loop is just for 10 sec time out
buttonState2 = digitalRead(buttonPin2); // enter
buttonState = digitalRead(buttonPin); //up
buttonState1 = digitalRead(buttonPin1); // down
timepassed = (millis() - timenow);
delay(1000);
Serial.println(counter--);
if (timepassed >= 10000)
return 0;
}
while (buttonState2 != HIGH) { // do this until enter is pressed
buttonState2 = digitalRead(buttonPin2); // enter
buttonState = digitalRead(buttonPin); //up
buttonState1 = digitalRead(buttonPin1); // down
if (buttonState == HIGH) { // up
buttonPushCounter++;
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter);
}
if (buttonState1 == HIGH) { // down
buttonPushCounter-- ;
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter);
}
delay(700);
}
save_to_eeprom(20, buttonPushCounter); // save to address 20 tha value it can be negative
}
我的問題:有什麼辦法避免從EEPROM讀取更新?
我認爲從EEPROM中讀取正在減少壽命。如果它適合我的便利, – Jim
是的,應該是。您可以無限次讀取EEPROM。 – foolo