These example programs show you how to use the capacitive touch sensors with our CircuitPython Libraries that are part of adafruit-blinka. It is relatively straightforward to adapt the programs to do different things. Just change the lines with print "pressed".
Two versions of the code are provided. One will continuously print output to the terminal while the touch sensor is pressed. The other will only print output once, irrelevant of how long the pad is pressed. Both pieces of code will work with the momentary and toggle boards.
Code for 5-pad board can be found on the next page of the guide.
The software is exactly the same on all 40-pin and 20-pin Raspberry Pi models.
Make sure you have connected the boards using the wiring instructions in the previous section before continuing.
CircuitPython Library Setup
See CircuitPython Libraries on Raspberry Pi to get a fresh Raspberry Pi setup.
If you have a running Raspberry Pi with an up to date copy of Raspbian you can simply run the following command to install adafruit-blinka.
$ sudo pip3 install adafruit-blinka
# SPDX-FileCopyrightText: 2019 Mikey Sklar for Adafruit Industries # # SPDX-License-Identifier: MIT import time import board from digitalio import DigitalInOut, Direction pad_pin = board.D23 pad = DigitalInOut(pad_pin) pad.direction = Direction.INPUT while True: if pad.value: print("pressed") time.sleep(0.1)
Single Output
This version of the Python code will only print an output once each time the sensor detects a touch.# SPDX-FileCopyrightText: 2019 Mikey Sklar for Adafruit Industries # # SPDX-License-Identifier: MIT import time import board from digitalio import DigitalInOut, Direction pad_pin = board.D23 pad = DigitalInOut(pad_pin) pad.direction = Direction.INPUT already_pressed = False while True: if pad.value and not already_pressed: print("pressed") already_pressed = pad.value time.sleep(0.1)
Running the Code
Open a terminal on your Pi.
Pull Down the two scripts directly onto your Raspberry Pi using wget.
$ wget https://raw.githubusercontent.com/adafruit/Adafruit_Learning_System_Guides/master/Capacitive_Touch_Sensors_on_the_Raspberry_Pi/Continuous_Output.py $ wget https://raw.githubusercontent.com/adafruit/Adafruit_Learning_System_Guides/master/Capacitive_Touch_Sensors_on_the_Raspberry_Pi/Single_Output.py
Run the code using the following commands. Try tapping vs holding your finger on the keypad. You should see "pressed" output in continuous mode or per tap depending on the script.
$ sudo python3 ./Continuous_Output.py
$ sudo python3 ./Single_Output.py
Text editor powered by tinymce.