How cool would it be if your microcontroller could work just by your touch? But then touch sensors are priced high and might not fit in the budget for a small DIY project. But hey? Don't be sad just yet, what if I tell you that the ESP32 microcontroller has a capacitive touch sensor! Yes, you heard that right, a touch sensor on a microcontroller!

A capacitive sensor is a proximity sensor that detects nearby objects by their effect on the electrical field created by the sensor.

There are 10 pins in the ESP32 board that can be assigned as a capacitive touch sensor. The available pin numbers are 0, 2, 4, 12, 13 14, 15, 27, 32, 33. Trying to assign any other pin as a capacitive touch sensor will result in an error. The TouchPad class of the machine module is to be used for assigning pins as touch sensors.

Let us now go through a simple example of how to print a message when the sensor is touched.

NOTE: All commands should be run in REPL prompt.

Step 1: Import the TouchPad and Pin class from machine module.

from machine import TouchPad,Pin

Step 2: Assign pin number 14 to be the capacitive touch sensor.

sensor = TouchPad(Pin(14))

Step 3: Read the sensor readings until the sensor is touched.

while True:

NOTE: will return a value even when the sensor is not touched, this value is close to 1000. The value when the sensor is touched is below 500. But depending upon the manufacturer of the board, these threshold values have to be determined by the user.

Step 4: Print a message when touch is detected.

    if (<500):
        print("You just touched pin number 14!")

The complete micropython program:

Note: Run the following program with ampy and NOT in the REPL prompt.

from machine import TouchPad,Pin
sensor = TouchPad(Pin(14))
while True:
    if ( < 500):
        print("You just touched pin number 14!")

Run it with ampy with the following command (save the program in a file and name the file

ampy --port /dev/ttyUSB0 run


You can now think of more ways to creatively use the touch sensor!

Psssst, want to control a LED by touch? Stay tuned!



Please do let us know if we are missing any topic or you want us to elaborate any topic, comment below and subscribe to be updated.