Example Code for Raspberry Pi – Digital Touch Sensor

Last revision 2026/01/20

Explore the practical application of a digital touch sensor with Raspberry Pi to control LEDs, featuring detailed setup instructions, connection guides, and Python programming using Thonny IDE for capacitive sensing.

Introduction

This is a touch switch module based on capacitive sensing that can sense the direct contact of the human body or metal on its metal surface. In addition to the direct touch, the contact with a certain thickness of plastic, glass and other materials can also be sensed. And its sensitivity depends on the size of the contact surface and the thickness of the covering material.

We are already clear about the control of Led. Now we are going to use Thonny Python IDE and the basic Python code operating GPIO to control Led by this digital analog sensors.

Hardware Preparation

Wiring Diagram

  • Connect the Raspberry Pi correctly to devices such as the screen, power, keyboard and mouse.

  • Install the Raspberry Pi IO expansion board on the Raspberry Pi, connect the LED light-emitting module digital port 12 on the board, and the digital analog sensor to port 8, then turn on the Pi.

**If there is a metal object or a finger touches the metal piece, pin 8 inputs a high level and triggers a high level on the pin 12, and the LED is on. When there is no metal object or finger touch, the pin 12 is low and the LED is off. **

Sample Code

  • Open Thonny Python IDE to copy the following program into it


import RPi.GPIO as GPIO    # Import the python module provided by the Raspberry Pi
import time    # Import time package for touch time detection

LED=12          # Define the pin number to which the LED is connected
KEY=8           # Define the pin number to which the sensor is connected

GPIO.setmode(GPIO.BCM)        # Set GPIO mode, BCM mode is common to all Raspberry Pi 
GPIO.setup(LED,GPIO.OUT)    # Set GPIO12 to output mode
GPIO.setup(KEY,GPIO.IN)    # Set GPIO8 to input mode

while True:        # Execute the following commands in an infinite loop
    if GPIO.input(KEY):        # GPIO.input(KEY)will return the state of GPIO and judge, if GPIO8 is high (i.e. The sensor received signal)
         GPIO.output(LED,GPIO.HIGH)      #Set LED signal pin high (Light LED on)
   else :          # If GPIO8 is low (Not receive signal)
     GPIO.output(LED,GPIO.LOW)   #Set LED signal pin low (Turn LED off)
time.sleep(0.1)   # Delay one second, here is to control the frequency of the query key

Was this article helpful?

TOP