/* 此例中我使用的 button 為常閉型(若設置為pull-up模式則在按鈕未按下時為 LOW)
#define button_pin 2
volatile unsigned long current_time = 0; //單位:msec
volatile unsigned long duration_time = 0; //單位:sec
volatile unsigned int start_flag = 0;
volatile unsigned long last_interrupt_time = 0;
volatile unsigned long interrupt_time = 0;
void buttonPressed(){
/* 外部中斷 + debounce + 按鈕釋放時觸發 */
interrupt_time = millis();
if ( (interrupt_time - last_interrupt_time > 300) && !digitalRead(button_pin) ){
/* ----- 主體開始 ----- */
if (!start_flag){
Serial.println("Start");
start_flag = 1;
current_time = millis();
}
else{
duration_time = (millis() - current_time)/1000;
if ( duration_time <= 60 ){
// 仿傳統 C 語言的格式化輸出
String text = String("") + "duration_time : " + duration_time + "sec";
Serial.println(text);
}
else{
String text = String("") + "duration_time : "
+ duration_time/60 + "min " + duration_time%60 + "sec";
Serial.println(text);
}
current_time = millis();
}
/* ----- 主體結束 ----- */
last_interrupt_time = interrupt_time;
}
}
void setup()
{
Serial.begin(115200);
pinMode(button_pin,INPUT_PULLUP);
attachInterrupt(0, buttonPressed, CHANGE); //外部中斷0 = pin2
}
void loop() {
}
我將定期推出程式語言的新手教學影片