#include <EEPROM.h> // library to access the onboard EEPROM
const int debounceTime = 15000; // debounce time in microseconds
int buttonPin = 5; // pushbutton connected to digital pin 5
int eeAddress = 0; // Address in the eeprom to store the data.
volatile unsigned long time; // variable to store the time since the program started
volatile boolean timeRecorded = false; // used to know when to save value
volatile unsigned long last_Rising; // used to debounce button press
void setup()
{
pinMode(buttonPin, INPUT); // sets the digital pin 5 as input
attachInterrupt(buttonPin, debounce, RISING);
}
void loop()
{
// Only want write when a time is saved
if(valueRecorded)
{
EEPROM.put(eeAddress, time);
valueRecorded = false;
}
}
void debounce()
{
if((micros() - last_Rising) >= debouncing_time)
{
getTime(); // call actual method to fetch and save time
last_Rising = micros();
}
}
void getTime()
{
time = millis();
valueRecorded = true;
}
1 回答
这个答案做出以下假设:
此代码使用中断来捕获从"off"到"on"的转换 . 开关的机械特性要求对输入进行去抖动(https://en.wikipedia.org/wiki/Switch#Contact_bounce) .
要从eeprom中读取值,您同样会使用
EEPROM.get( eeAddress, time)
这会将保存在eeprom中的值放在变量time
中 .此代码也没有规定处理实际的日历时间 . 在Arduino游乐场(http://playground.arduino.cc/code/time)有一个时间库,虽然它已经过时了 . "Time"库链接到该页面,并提供有关如何使用它来提供日历时间的文档,但是,每次重新启动Arduino时都需要设置和同步时间 .