我想写下按钮打开或关闭的时间。
每次有人打开开关,Arduino就会存储这个信息。
#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;
}
这个答案做了以下假设:
- Arduino Uno正在被使用。
-瞬间开关(或按钮)连接到数字引脚5,当开关处于"开"位置时,5v信号将应用于引脚5,当开关处于"关"位置时,0v信号将应用于引脚5。
-你的目标是写入板载eeprom的时间,按钮改变状态的最后一次发生。
这段代码使用一个中断来捕捉从"off"到"on"的转换。开关的机械特性要求对输入进行脱耦(https://en.wikipedia.org/wiki/Switch#Contact_bounce)。
要从eeprom中读取值,您将类似地使用EEPROM.get( eeAddress, time)
,这将把保存在eeprom中的值放在变量time
中。
这段代码也没有处理实际日历时间的规定。有一个时间库在Arduino操场(http://playground.arduino.cc/code/time),虽然它显然是过时的。一个"时间"库被链接到该页上,并有关于如何使用它来提供日历时间的文档,但是,每次重新启动Arduino时,时间需要设置和同步。