醬是創客的ESP32教學主題第八篇,以Ai-Thinker安信可NodeMCU-32S(使用Arduino語言)來實作教學,本篇教學將著重Arduino偵測GPIO按鈕壓下時間並控制Reset Default或重新機,如同網路路由器的reset功能,長按會清除所有設定資料,短按會重開機,本篇以簡單硬體和程式碼來實作
以下是我們今天的目標
- 使用GPIO 15搭配pinMode為INPUT來偵測高低電位
- 高電位不觸發。當按鈕壓下時導通變為低電位,此時觸發。
- 按下時間 <5秒,重開機,並印出less 5s time
- 按下時間 >5秒,重開機,並印出more 5s time
NodeMCU-32S電路接線圖如下
- 3.3V–電阻(12K歐姆)–GPIO15–電阻(470歐姆)–按紐(Botton)–GND
- 按紐(Botton)為按下導通,沒有按下不導通
Arduino 範例程式碼如下
//醬是創客 開發實作的好夥伴 #include "WiFi.h" //task unsigned long currentMillis = 0; unsigned long previousMillisReset_1 = 0; unsigned long previousMillisReset_2 = 0; int intervalReset = 5000; //button int inPin = 15; bool button_15_status; bool previous_button_15_status = HIGH;//HIGH byte button_press_counter = 0; void setup() { Serial.begin(115200); //Button pinMode(inPin, INPUT); } void loop() { currentMillis = millis(); reset_default_button(); } void reset_default_button() { button_15_status = digitalRead(inPin); if (button_15_status == HIGH) { if (button_15_status != previous_button_15_status){ //按下超過5秒 if ((unsigned long)(previousMillisReset_2 - previousMillisReset_1) >= intervalReset) { Serial.println("more 5s time: "); Serial.println(previousMillisReset_2 - previousMillisReset_1); previous_button_15_status = button_15_status; //重開機 ESP.restart(); } //按下小於5秒 else { Serial.println("less 5s time: "); Serial.println(previousMillisReset_2 - previousMillisReset_1); previous_button_15_status = button_15_status; //重開機 ESP.restart(); } } previous_button_15_status = HIGH; } else { if(button_press_counter == 0){ previousMillisReset_1 = currentMillis; previousMillisReset_2 = currentMillis; button_press_counter = 1; } else{ previousMillisReset_2 = currentMillis; } previous_button_15_status = LOW; } }
當按鈕按下小於5秒
less 5s time: 1786 ets Jun 8 2016 00:22:57 rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT) configsip: 0, SPIWP:0xee clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00 mode:DIO, clock div:1 load:0x3fff0018,len:4 load:0x3fff001c,len:1044 load:0x40078000,len:8896 load:0x40080400,len:5816 entry 0x400806ac
當按鈕按下大於5秒
more 5s time: 6924 ets Jun 8 2016 00:22:57 rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT) configsip: 0, SPIWP:0xee clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00 mode:DIO, clock div:1 load:0x3fff0018,len:4 load:0x3fff001c,len:1044 load:0x40078000,len:8896 load:0x40080400,len:5816 entry 0x400806ac