《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 的作用很多,还需进一步探索。

猜你喜欢

转载自blog.csdn.net/qq_41868901/article/details/106233643