首页 文章

在Arduino上写EEPROM阵列

提问于
浏览
0

我想写下打开或关闭按钮的时间 .

每当有人打开开关时,Arduino都会存储这些信息 .

1 回答

  • 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 Uno .
    • 瞬时开关(或按钮)连接到数字引脚5,这样当开关处于"on"位置时,5v信号将施加到引脚5,当开关处于开关状态时,0v信号将施加到引脚5 "off"的位置 .
    • 你的目标是在最后一次按钮改变状态的时间写入板载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)有一个时间库,虽然它已经过时了 . "Time"库链接到该页面,并提供有关如何使用它来提供日历时间的文档,但是,每次重新启动Arduino时都需要设置和同步时间 .

相关问题