我想写下按钮打开或关闭的时间。
每次有人打开开关时,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,这样当开关处于“打开”位置时,引脚 5 将施加 5v 信号,而当开关处于“打开”位置时,引脚 5 将施加 0v 信号处于“关闭”位置。
- 您的目标是将按钮最后一次更改状态的时间写入板载 eeprom。
此代码使用中断来捕获从“关闭”到“开启”的转换。开关的机械特性需要对输入进行去抖动(https://en.wikipedia.org/wiki/Switch#Contact_bounce)。
要从 eeprom 中读取值,您将类似地使用EEPROM.get( eeAddress, time)
这会将保存在 eeprom 中的值放入变量中time
。
这段代码也没有规定处理实际的日历时间。Arduino 游乐场 ( http://playground.arduino.cc/code/time ) 中有一个时间库,尽管它显然已经过时了。该页面上链接了一个“时间”库,并包含有关如何使用它来提供日历时间的文档,但是,每次重新启动 Arduino 时都需要设置和同步时间。