2015-08-26 131 views

回答

0
#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的乌诺。
- 将一个瞬时开关(或按钮)连接到数字引脚5,使得当开关处于“导通”位置时,5v信号将被施加到引脚5,而0v信号将被施加到引脚5时开关处于“关”的位置。
- 您的目标是在机载eeprom中记录上次发生按钮更改状态的时间。

此代码使用中断来捕捉从“关”到“开”的转换。开关的机械特性需要去除输入(https://en.wikipedia.org/wiki/Switch#Contact_bounce)。

要从eeprom中读取值,您将同样使用EEPROM.get(eeAddress, time)这会将保存在eeprom中的值存储在变量time中。

此代码也没有规定处理实际的日历时间。Arduino游乐场有一个时间库(http://playground.arduino.cc/code/time),虽然它显然过时了。一个“时间”库链接到该页面上,并具有如何使用它提供日历时间的文档,但是,每次重新启动Arduino时都需要设置和同步时间。