2013-01-01 161 views
3

我正在用arduino进行我的第一个物理计算项目,实际上是一个seeduino stalker 2.1。我正在建立一个记录水收集率的设备。Arduino循环和闹钟

项目的建立和运行并没有那么艰难,直到今天。在主循环中,我调用了一个处理日志记录的方法。我现在还有一个警报延迟来处理我需要的定时器重复,以汇总数据并通过短信发送给收件人号码。

问题是,当alarm.repeat()处于活动状态时,它会抢占数据的记录。问题是:当alarm.delay存在时,为什么循环内部的日志方法不工作?

void setup() { 
    Serial.begin(9600); 
    Wire.begin(); 
    setTime(1,17,0,1,1,13); // set time 
    Alarm.timerRepeat(60, Repeats); //set repeater 

} 

void loop(){ 
    logging(); //call logging 
    Alarm.delay(1300); //for repeater 
} 

void Repeats(){ 
    Serial.println("the repeater fired"); // just to see it working 
} 

void logging(){ 

    val = digitalRead(Sensor_Pin); // read Sensor_Pin 
    if (val == HIGH) {   
    // If Sensor N.C. (no with magnet) -> HIGH : Switch is open/LOW : Switch is closed 
    // If Sensor N.0. (nc with magnet) -> HIGH : Switch is closed/LOW : Switch is open 
    digitalWrite(Led_Pin, LOW); //Set Led low 
    //Serial.print("status -->"); 
    //Serial.println("low"); 
    //delay(500); 
    } else { 
    digitalWrite(Led_Pin, HIGH); //Set Led high 
     logdata(); 
    } 
} 

void logdata(){ 

    // open the file. note that only one file can be open at a time, 
    // so you have to close this one before opening another. 
    File myFile = SD.open("datalog.txt", FILE_WRITE); 

    // if the file opened okay, write to it: 
    if (myFile) { 

     //DateTime now = RTC.now(); 
     //String myString = readTimestamp(now); 
     time_t t = now(); 
     String aDate = String(year(t))+"/"+String(month(t))+"/"+String(day(t))+" "+String(hour(t))+":"+String(minute(t))+":"+String(second(t)); 
     myFile.println(aDate); 
    // close the file: 
     myFile.close(); 
     Serial.println(aDate); 
     delay(500); } else { 
     // if the file didn't open, print an error: 
     // Serial.println("error opening DATALOG.TXT"); 
    } 
} 
+0

什么是报警库? – Ian

回答

1

问:我为什么一定要用Alarm.delay(),而不是延迟()?答:在Alarm.delay功能中处理任务调度 。监控任务并在Alarm.delay调用中触发 ,因此Alarm.delay应为 ,只要草图中需要延迟。如果您的草图 等待外部事件(例如传感器更改),请确保 在检查传感器时重复调用Alarm.delay。

从报警库的FAQ。所以它看起来像Alarm.Delay就像标准延迟,但可以被排定的事件中断。您的日志记录调用没有安排,它只发生在循环的开始。 ..你的日志根本没有发生?看起来应该在每个循环开始时调用它,然后在延迟期间延迟器触发1300个延迟。

0

在您的logdata()函数上,您调用的是delay(50)而不是Alarm.delay(50)

正如您指出的那样,当需要延迟时,您必须使用Alarm.delay,否则延迟会与闹钟混淆。

0

我想你可以用其他方式使用计时器库。如果您说数据必须每秒记录一次,则更容易通过定时器完成。示例代码

#include <SimpleTimer.h> 

// the timer object 
SimpleTimer timer; 

// a function to be executed periodically 
void repeatMe() { 
    Serial.print("Uptime (s): "); 
    Serial.println(millis()/1000); 
} 

void setup() { 
    Serial.begin(9600); 
    timer.setInterval(1000, repeatMe); 
} 

void loop() { 
    timer.run(); 
}