Let's get started with the PiicoDev ® Capacitive Touch Sensor. In this guide, we'll connect the PiicoDev Capacitive Touch Sensor to our Raspberry Pi Pico and get it working with some example code to detect touch events. We'll also remix the code so we may cover the sensor with a pretty label - and finally, we'll make a simple light controller during the remix section.
To follow along, it's best to have:
- A Raspberry Pi Pico with pins soldered (pointing down)
- A PiicoDev Capacitive Touch Sensor CAP1203
- A PiicoDev Expansion Board for Raspberry Pi Pico
- A PiicoDev Cable
- (Optional) A PiicoDev platform helps secure everything together.
- (Optional) Alligator Clips to use other objects as touch sensors.
- (Optional) A GlowBit® Rainbow or other LED device to use as a display - this one needs some special alligator-to-pin-header leads.
If you prefer not to use the Expansion Board for Raspberry Pi Pico, there are other connection options in our PiicoDev Connection Guide.
Contents
- Introduction
- Connect the Sensor to your Pico
- Download MicroPython Modules
- Example Code - Read Touch Status
- Setup Options - Single/Multi-Touch and Tune Sensitivity
- Remix - Colour Mixer
- Conclusion
- Resources
Introduction
The PiicoDev Capacitive Touch Sensor has three copper pads on it (labelled 1, 2 and 3) that work like three separate buttons. Touching one of the touchpads changes its capacitance and this change is measured by the CAP1203 device which registers it as a touch event. The device is capable of registering multiple touch events at the same time or filtering for just the first event. We can also tune the touch sensitivity which is useful if we want to cover the sensor or connect alligator clips and detect touch with some remote objects
Connect the PiicoDev Capacitive Touch Sensor to your Pico
Plug your Pico into the Expansion Board, connect your touch sensor to the Expansion Board via the PiicoDev cable, and finally connect your Pico to your computer with a USB lead.
If you're unfamiliar with connecting PiicoDev modules, read the PiicoDev Connection Guide before proceeding.
Download MicroPython modules
We will need three files to easily read data from the Capacitive Touch Sensor:
- Download the PiicoDev Unified Library: PiicoDev_Unified.py (right-click, "save link as").
- Download the device module: PiicoDev_CAP1203.py (right-click, "save link as")
- Download the example script: main.py (right-click, "save link as")
It will be best to keep these files wherever you like to keep your coding projects eg. Documents > PiicoDev
Example Code - Read Touch Status
We'll be working in Thonny - if you're unfamiliar working with Thonny see our guide for Thonny and Raspberry Pi Pico.
Open Thonny, connect to your Pico and navigate to where you stored the files from the last step. Right-click each file and select "Upload to /" to upload them to your Pico (Hint: View the files menu with View > Files)
Restart your Pico (Keyboard shortcut, Ctrl+D) and you should see your Pico printing "Touch Pad Status" data in the shell. When you touch a pad, the corresponding number should change from zero to one.
Above: Touch Status data streams up the Shell, while the Plot (bottom-right) shows historic data. The plot shows the pads (Blue: 1, Yellow: 2, Red: 3) are pressed and released in sequence, and then I slide my finger slowly across pads #1 and #2 which registers as two independent events.
In this example, the status of each pad is assigned into a Python dict variable called status, and we access the status for pad 1, 2 or 3 with that key, eg. status[1] retrieves the status of Touchpad #1. Status is zero when the pad is not touched, and one when it is being touched.
Setup options
By default, the PiicoDev Capacitive Touch Sensor is initialised in multi-touch mode with a good all-rounder sensitivity level. You can change these settings depending on how you initialise the device to use single-touch mode or increase/decrease the sensitivity.
Single-Touch mode
The following initialisation will set the sensor up to reject multiple touch events and return only the first touch event.
touchSensor = PiicoDev_CAP1203(touchmode='single')
Sensitivity
Tuning the sensitivity can allow the sensor to detect touch events from behind another object eg. a piece of paper or plastic. This can be useful if you want to put a nice label over your sensor or conceal it behind a (thin-walled) enclosure. Tuning the sensitivity is also necessary if you want to use the alligator clip terminals to connect an external object to the sensor. There are eight sensitivity levels, with 0 being most sensitive, and 7 being least sensitive. The default sensitivity is 3. The initialisation would look something like this:
touchSensor = PiicoDev_CAP1203(sensitivity=6)
It's always best to power-cycle the circuit whenever you change the touch characteristics by eg. covering a touch pad or connecting an object with an alligator clip. On powerup, the CAP1203 performs a self-calibration which will make the best use of your new sensitivity setting.
Above: Using coloured paper to create fancy labels for a touch sensor. You can also connect other objects to the touch sensor using alligator clips - conductive or organic objects like fruit & veg work best. You may need to tune the sensitivity to get other objects to work reliably.
Of course, the initialisation options can be combined to set touchmode and sensitivity at the same time eg.
touchSensor = PiicoDev_CAP1203(touchmode='single', sensitivity=6)
Remix - Colour Selector
We'll remix the example program to change the colour of some LEDs depending on what pad is pressed. I'll use a GlowBit Rainbow in this demonstration - any WS2812Bv5 LEDs will work. if you don't have access to any, there is still a print statement that will indicate which part of the program is running. For help with wiring a Rainbow to a Pico, follow our guide.
Run the following code on your Pico, either by using the run button or saving it as main.py to your Pico. This program reads the status of each touch pad, and assigns the colour Red to Pad #1, Green to Pad #2, and Blue to Pad #3. By touching a pad, you can make that colour appear on the LEDs. Touching multiple pads will mix those colours, eg. Pad #1 + Pad #2 = Red + Green = Yellow.
# Change the colour of GlowBit LEDs using touch buttons. # Requires a GlowBit rainbow or other device that uses WS2812Bv5 LEDs import array, time from machine import Pin import rp2 from PiicoDev_CAP1203 import PiicoDev_CAP1203 from PiicoDev_Unified import sleep_ms # cross-platform-compatible sleep touchSensor = PiicoDev_CAP1203(touchmode='multi', sensitivity=6) # Initialise in multi-touch mode so we can mix colours. Low sensitivity keeps away bugs # Configure the number of WS2812 LEDs. NUM_LEDS = 13 PIN_NUM = 22 brightness = 1 # WS2812B LED Driver code ########################################################################## @rp2.asm_pio(sideset_init=rp2.PIO.OUT_LOW, out_shiftdir=rp2.PIO.SHIFT_LEFT, autopull=True, pull_thresh=24) def ws2812(): T1 = 2 T2 = 5 T3 = 3 wrap_target() label("bitloop") out(x, 1) .side(0) [T3 - 1] jmp(not_x, "do_zero") .side(1) [T1 - 1] jmp("bitloop") .side(1) [T2 - 1] label("do_zero") nop() .side(0) [T2 - 1] wrap() # Create the StateMachine with the ws2812 program, outputting on pin sm = rp2.StateMachine(0, ws2812, freq=8_000_000, sideset_base=Pin(PIN_NUM)) # Start the StateMachine, it will wait for data on its FIFO. sm.active(1) # Display a pattern on the LEDs via an array of LED RGB values. ar = array.array("I", [0 for _ in range(NUM_LEDS)]) ########################################################################## def pixels_show(): dimmer_ar = array.array("I", [0 for _ in range(NUM_LEDS)]) for i,c in enumerate(ar): r = int(((c >> 8) & 0xFF) * brightness) g = int(((c >> 16) & 0xFF) * brightness) b = int((c & 0xFF) * brightness) dimmer_ar[i] = (g<<16) + (r<<8) + b sm.put(dimmer_ar, 8) time.sleep_ms(10) def pixels_set(i, color): ar[i] = (color[1]<<16) + (color[0]<<8) + color[2] def pixels_fill(color): for i in range(len(ar)): pixels_set(i, color) while True: status = touchSensor.read() r = 255 * status[1] # Button 1 controls the red channel g = 255 * status[2] # Button 2 controls the green channel b = 255 * status[3] # Button 3 controls the blue channel pixels_fill( (r,g,b) ) # fill every LED with the RGB colour chosen pixels_show() if status[1] == 1: print("red ",end="") if status[2] == 1: print("green ",end="") if status[3] == 1: print("blue",end="") print("") # new line sleep_ms(100)
Conclusion
We can detect touch events using a PiicoDev Capacitive Touch Sensor. By changing the touch mode or sensitivity, we can tune the sensor for different applications like detecting touch through a label, or through an enclosure. We can also trigger certain program behaviour like printing different messages or showing different colours with an LED.
If you make something cool with this starter project we'd love for you to share it on our forums! And if you'd like some help with this guide, start the conversation below - We're full-time makers and here to help!