/*
* A.3 可以掌控執行時間的迴圈
* 使用Arduino AVR MCU.. (UNO,MEGA.. )
*/
#include <avr/sleep.h>.
#include <avr/wdt.h>
#define VERSION "ARDUINO STATE MACHINE 2022 00"
#define DEBUG 1
#if(DEBUG)
#define DEBUGP(x) Serial.print(x)
#define DEBUGN(x) Serial.println(x)
#else
#define DEBUGP(x)
#define DEBUGN(x)
#endif
//HZ Control
#define HZ_SETTING 10
int mainLoop_count;
unsigned long fast_loopTimer; // Time in miliseconds of main control loop
const int hzCount = (1000 / HZ_SETTING)-1;
const int timeRemind = 1000 / HZ_SETTING;
void(* resetFunc) (void) = 0; //declare reset function @ address 0 call resetFunc(); if you want to reset
#define LED_PIN 13
void hw_init(){
// 啟動Serial
Serial.begin(115200);
// 初始化 IO
pinMode(LED_PIN,OUTPUT);
}
void setup() {
//Setup I/O
hw_init();
//setup WDT
wdt_enable(WDTO_4S);
}
int secCount =0;
void loop() {
if (millis()-fast_loopTimer > hzCount) {
fast_loopTimer = millis();
mainLoop_count++;
wdt_reset(); // Reset WDT ...
/// do things ********************************************************************
Serial.println(mainLoop_count);
if(mainLoop_count%HZ_SETTING==0){
secCount++;
mainLoop_count = 0;
DEBUGP("1 S :");
DEBUGN(secCount);
digitalWrite(LED_PIN,!digitalRead(LED_PIN));
}
// Time Remind for this Loop ------------------------------------------
DEBUGP("Time Remind ms :");
DEBUGN(timeRemind - (millis()-fast_loopTimer));
}
}