《ESP32 學習筆記》 之Arduino環境下 觸摸按鍵-Touch 檢測

1.簡介

在 Arduino環境下,我們如何用 ESP32的觸摸按鍵 功能 ?

Touch 就像 ADC 檢測一樣,很玄學,可以用來解決一些很神奇的問題,比如全國電賽中紙張數目檢測的題目,就可以根據ADC檢測的電壓值來判斷紙張數目。

在本次實驗中,我們使用了源文件:esp32-hal-touch.h 和 esp32-hal-touch.c  

esp32-hal-touch.h源文件:

/*
 * Set cycles that measurement operation takes
 * The result from touchRead, threshold and detection
 * accuracy depend on these values. Defaults are
 * 0x1000 for measure and 0x1000 for sleep.
 * With default values touchRead takes 0.5ms
 * */
void touchSetCycles(uint16_t measure, uint16_t sleep);

/*
 * Read touch pad (values close to 0 mean touch detected)
 * You can use this method to chose a good threshold value
 * to use as value for touchAttachInterrupt
 * */
uint16_t touchRead(uint8_t pin);

/*
 * Set function to be called if touch pad value falls
 * below the given threshold. Use touchRead to determine
 * a proper threshold between touched and untouched state
 * */
void touchAttachInterrupt(uint8_t pin, void (*userFunc)(void), uint16_t threshold);

 注:支持 Touch 功能的引腳請查看:引腳定義,查找對應引腳的Touch通道。

2.硬件平臺

安信可 NODEMCU-32S 開發板:

3.軟件平臺

Arduino (1.8.10)     或     VScode 環境下 PlatformIO 插件

4.示例程序

在測試時,可以給 ESP32 的引腳上插上一根 公對母杜邦線 ,使用時,用 手觸摸杜邦線的公頭端即可。

4.1 直接讀取觸摸引腳值

/**
 * 時間:2020/5/18
 * 作者:劉澤文
 * 功能:使用ESP32的觸摸按鍵
 */
#include <WiFi.h>

void setup() {
  Serial.begin(115200);
  delay(1000);
  Serial.println("Starting Touch work!");
  
}

void loop() {
  Serial.println(touchRead(T0));  // Touch0 通道是 GPIO 4.
  delay(30);
}

4.2 觸摸按鍵中斷

/**
 * 時間:2020/5/18
 * 作者:劉澤文
 * 功能:使用ESP32的觸摸按鍵中斷
 */
#include <WiFi.h>

#define LED 2

bool LED_st = true;

void gotTouch(){
  delay(10);
  LED_st = !LED_st;
}

void setup() {
  Serial.begin(115200);
  delay(1000);
  Serial.println("ESP32 Touch Interrupt Test");
  pinMode(LED,OUTPUT);
  digitalWrite(LED,HIGH);
  touchAttachInterrupt(T0, gotTouch, 40);//其中40爲閾值,當通道T0上的值<40時,會觸發中斷
}

void loop(){
  delay(300);
  digitalWrite(LED,LED_st);//狀態反轉
}

5.總結

在日常使用中,可以先使用 touchRead(T0) 來確定 touchAttachInterrupt() 的閾值,Touch 的作用很多,還需進一步探索。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章