專注電子技術(shù)學(xué)習(xí)與研究
當(dāng)前位置:單片機(jī)教程網(wǎng) >> Arduino >> 瀏覽文章

Arduino的Watchdog Timer

作者:y8686   來源:轉(zhuǎn)自y8686   點(diǎn)擊數(shù):  更新時(shí)間:2014年07月12日   【字體:

 看門狗! 聽起來就足夠“高大上”的。

 
曾一度以為Arduino有bootloader就不會(huì)有watchdog了,但是事實(shí)上是有的。 
 
我參考了如下兩個(gè)鏈接:
http://tushev.org/articles/arduino/item/46-arduino-and-watchdog-timer
http://blog.csdn.net/chn89/article/details/17199171
 
然后寫了如下代碼實(shí)驗(yàn)。
 
該代碼正常情況下啟動(dòng)watchdog,并設(shè)定watchdog定時(shí)器為1s。 loop里面每次循環(huán)開始的時(shí)候“喂狗”。
主循環(huán)loop里有按鍵檢測(cè),檢測(cè)到pin#7上的按鍵按下就切換pin#13上的LED狀態(tài),啟動(dòng)時(shí)默認(rèn)LED熄滅。
如果檢測(cè)到串口有數(shù)據(jù)輸入則進(jìn)入死循環(huán),watchdog定時(shí)器1s到時(shí)間后會(huì)自動(dòng)重啟。
 
實(shí)驗(yàn),燒入程序后,按按鍵使得LED亮起,然后在電腦上打開串口終端,發(fā)送任何字符,1秒后LED會(huì)熄滅(重啟后的LED初始狀態(tài)),表示arduino重啟了。
 
 
 
C語言: 高亮代碼由發(fā)芽網(wǎng)提供


#include

#define BUTTON_PIN          7       // Button pin
#define LED_PIN             13      // Led pin
#define BUTTONS_SAMPLES     6000   // Affect the sensitivity of the button
#define BUTTON_PRESSED      LOW     // The state of the pin when button pressed

unsigned int o_prell          0;      // counter for button pressing detection
boolean button_state          = false;  
unsigned int led_state        = LOW;    // Led off at the beginning

void setup()
{
   Serial.begin(9600);

   pinMode(BUTTON_PIN, INPUT);
   pinMode(LED_PIN, OUTPUT);
   
   // set initial LED state
   digitalWrite(LED_PIN, led_state);

   wdt_enable(WDTO_1S);    // enable the watchdog timer : 1 second timer
}

void loop()
{
   wdt_reset();    // feed the dog

   check_button();
   digitalWrite(LED_PIN, led_state);

   if (Serial.available()>0)
   {
       while(1) ;
   }
}

void check_button()
{
   int button_input    =   digitalRead(BUTTON_PIN);

   if ((button_input == BUTTON_PRESSED) && (o_prell <</SPAN> BUTTONS_SAMPLES))
   {
       o_prell++;      // counting for button pressing
   }
   else if ((button_input == BUTTON_PRESSED) && (o_prell == BUTTONS_SAMPLES) && !button_state)
   {
       button_state = true;    // button pressed
       //led_state = HIGH;
       led_state = !led_state;
   }
   else if ((button_input != BUTTON_PRESSED) && (o_prell > 0))
   {
       o_prell--;      // counting for button releasing,  or debouncing / immunity
   }
   else if ((button_input != BUTTON_PRESSED) && (o_prell == 0) && button_state)
   {
       button_state = false;
       //led_state = LOW;
   }
}
關(guān)閉窗口

相關(guān)文章