레이블이 터치 센서인 게시물을 표시합니다. 모든 게시물 표시
레이블이 터치 센서인 게시물을 표시합니다. 모든 게시물 표시

2018년 11월 9일 금요일

ESP32에서 터치센서 사용하기 (Using ESP32 Capacitive Touch Sensor)



이전 포스트(ESP32 GPIO 레퍼런스)에서 소개했던 것 처럼 ESP32에는 총 10개의 터치 센서가 들어 있다. 이를 사용하면 아무런 추가 하드웨어 없이 터치 스위치를 만들 수 있다. 10개 터치 센서의 핀 매핑은 다음과 같다.

static const uint8_t T0 = 4;
static const uint8_t T1 = 0;
static const uint8_t T2 = 2;
static const uint8_t T3 = 15;
static const uint8_t T4 = 13;
static const uint8_t T5 = 12;
static const uint8_t T6 = 14;
static const uint8_t T7 = 27;
static const uint8_t T8 = 33;
static const uint8_t T9 = 32;

사용법 역시 매우 간단하다. 푸쉬버튼을 사용하는 경우 먼저 setup()에서 스위치가 연결된 핀을 pinMode()로 설정을 해 주고 digitalRead()로 상태를 읽어야 하는데 터치의 경우 별도의 설정은 필요 없고 touchRead() 함수로 값을 읽으면 된다.

아래 예제 코드는 T0 (4번핀)를 터치 스위치로 사용해서 LED를 토글시키는 것이다.


#define TOUCH_SW T0    // connected to 4
#define LED A13        // connected to 15

int touchVal = 100;

void setup()
{
  Serial.begin(115200);
  Serial.println("ESP32 Touch Example");
  pinMode(LED, OUTPUT);
}

void loop()
{
  static boolean led_state = LOW;
  static boolean prevState = LOW; 
  static boolean touchState;

  touchVal = touchRead(TOUCH_SW);     // read touch switch state
  touchState = touchVal < 50 ? HIGH:LOW;
  if ((LOW == prevState) && (HIGH == touchState))  {    
    Serial.println("Switch touched");
    led_state = !led_state;
    digitalWrite(LED, led_state);      
  }
  prevState = touchState;
  delay(50);
}