Capacitive Touch Sensing Tutorial for PIC Microcontrollers

Capacitive touch sensing allows a microcontroller to detect the presence of a finger or conductive object without the need for moving parts. Many PIC microcontrollers include hardware modules or specialized peripheral libraries (such as mTouch®) that simplify implementing touch sensors on PCBs. In this tutorial, we will explore how to design and integrate a basic capacitive touch sensor using PIC microcontrollersIntroduction to PIC: Exploring the Basics of Microcontroller ArchitectureIntroduction to PIC: Exploring the Basics of Microcontroller ArchitectureExplore the core principles of PIC microcontroller architecture, including Harvard design, RISC processing, and efficient memory organization., focusing on key concepts, hardware design considerations, and code snippets to get started.

Overview of Capacitive Touch Sensing🔗

Capacitive sensing works by measuring changes in capacitance that occur when a finger (or other conductive object) approaches a sensorAnalog-to-Digital Conversion: Connecting Sensors to PICAnalog-to-Digital Conversion: Connecting Sensors to PICExplore our step-by-step PIC microcontroller ADC tutorial, including sensor interfacing techniques and C code examples to achieve accurate conversions. electrode. This capacitance change can be detected by:

A finger adds a small but measurable capacitance, causing a shift in measured value. The microcontroller's firmware can calculate whether this shift indicates a valid “touch.”

PIC Hardware Requirements🔗

Many PIC devices come with specific hardware resources for capacitive sensing. Some typical features:

When selecting a PIC for capacitive sensing, look for models highlighting built-in support for touch or consult the datasheet for available sensing peripherals.

Sensor Pad Design and PCB Layout🔗

Designing the physical sensorAnalog-to-Digital Conversion: Connecting Sensors to PICAnalog-to-Digital Conversion: Connecting Sensors to PICExplore our step-by-step PIC microcontroller ADC tutorial, including sensor interfacing techniques and C code examples to achieve accurate conversions. electrode (the pad) on the PCB is critical for accurate measurements. Consider the following:

1. Shape and Size

  • Typically use round or rectangular copper pads.
  • Maintain consistent size for uniform sensitivity.

2. Ground Guard Ring

3. Dielectric Layer

4. Trace Routing

Firmware Implementation Strategy🔗

Initialization

1. Set Up the PIC Clock

Configure the internal or external oscillator to run at a frequencyGenerating Audio with PIC Timers and PWMGenerating Audio with PIC Timers and PWMExplore how to configure PIC timers and PWM for audio signal generation, including hardware setup, duty cycle adjustments and simple tone creation. recommended for capacitive sensing (common frequencies include 4 MHz or 8 MHz, but check the datasheet and example application notes).

2. Configure I/O Ports

3. Enable Capacitive Sensing Hardware

  • If using CTMU: Enable it in firmware and configure the necessary reference current or timing settings.
  • If using a dedicated module: Initialize registers as per datasheet or use the library’s initialization function.

Capture and Processing

1. Measurement Cycle

2. Filtering and Debounce

  • Apply basic filtering (e.g., moving average) to eliminate noise.
  • Implement software debounce to avoid false touches from short spikes.

3. Threshold Detection

Example Code Snippet (Using CTMU on PIC)🔗

Below is a simplified example in C using the CTMU hardware on a generic PIC device that supports this module.

#include <xc.h>
// Configuration bits (example; configure per your device)
#pragma config FOSC = HSPLL
#pragma config WDT = OFF
#pragma config MCLRE = ON
// ... (other configuration bits as needed)
// Define the sensor pin
#define TOUCH_SENSOR_TRIS TRISBbits.TRISB0
#define TOUCH_SENSOR_ANSEL ANSELbits.ANS0
#define TOUCH_SENSOR_PIN  0 // RB0
void CTMU_Init(void) {
    // Enable CTMU module, configure current source, etc.
    CTMUCONH = 0x00;
    CTMUCONL = 0x00;
    CTMUICON = 0x03; // Example: set base current
    CTMUCONHbits.CTMUEN = 1; // Enable CTMU
    // Additional configuration as per device datasheet
}
unsigned int GetTouchReading(void) {
    unsigned int reading;
    // Charge sensor pad
    CTMUCONLbits.EDG1STAT = 1;  // Start charging
    __delay_us(5);             // Wait for a short period
    CTMUCONLbits.EDG1STAT = 0;  // Stop charging
    // Read ADC for the sensor pin
    // (Assuming we've configured the ADC on the same pin)
    // Example hypothetical function:
    reading = ReadADC(0); // Channel 0 = AN0 (RB0)
    return reading;
}
void main(void) {
    // Basic initialization
    TOUCH_SENSOR_TRIS = 1;   // Input mode
    TOUCH_SENSOR_ANSEL = 1;  // Analog mode (if required by CTMU)
    ADC_Init();  // Your custom function to init ADC
    CTMU_Init(); // Initialize CTMU
    while(1) {
        unsigned int sensorValue = GetTouchReading();
        // Decide if it's a valid touch
        if(sensorValue > 300) {
            // For instance, toggling an LED or performing an action
            // ... your handling code
        }
        __delay_ms(50); // Basic delay for poll-based approach
    }
}
Note: The exact register names and bit definitions will vary by PIC family. Always consult the official datasheet and reference manual for the specific device.

Testing and Calibration🔗

1. Initial Calibration

  • Measure the baseline capacitance in a “no-touch” environment for a certain period.
  • Store this value in memory as a reference.

2. Threshold Adjustment

  • Experiment with different threshold values to accommodate user variability.
  • If your environment is prone to electrical noise, add dynamic or adaptive thresholds.

3. Environmental Considerations

Best Practices for Reliable Touch Sensing🔗

  • Use Proper Grounding: Ensure a low-impedance ground reference, especially when using dedicated touch electrodes.
  • Shielding: In noisy environments, implement shielding to block interference.
  • Minimize Parasitic Capacitance: Excessive parasitic capacitance in the PCB or cables can reduce sensitivity.
  • Firmware Tuning: Consider adding a software signal filter (e.g., running average, median filter) to stabilize readings.
  • Prototyping: Always prototype on a board that carefully respects layout guidelines for capacitive sensing before moving to a final product.

Conclusion🔗

Integrating a touch sensorAnalog-to-Digital Conversion: Connecting Sensors to PICAnalog-to-Digital Conversion: Connecting Sensors to PICExplore our step-by-step PIC microcontroller ADC tutorial, including sensor interfacing techniques and C code examples to achieve accurate conversions. with a PIC microcontrollerIntroduction to PIC: Exploring the Basics of Microcontroller ArchitectureIntroduction to PIC: Exploring the Basics of Microcontroller ArchitectureExplore the core principles of PIC microcontroller architecture, including Harvard design, RISC processing, and efficient memory organization. using its built-in capacitive sensing features provides an elegant, modern interface solution. By carefully designing the sensorAnalog-to-Digital Conversion: Connecting Sensors to PICAnalog-to-Digital Conversion: Connecting Sensors to PICExplore our step-by-step PIC microcontroller ADC tutorial, including sensor interfacing techniques and C code examples to achieve accurate conversions. pad, applying the correct hardware and firmware configurations, and including sufficient filtering and calibration routines, you can achieve a robust and user-friendly touch interface. As you become comfortable with the principles outlined here, you can expand your design to incorporate multiple touch pads, sliders, or even advanced gesture detection-transforming any PIC-based project into a sleek, human-interactive system.

Author: Marcelo V. Souza - Engenheiro de Sistemas e Entusiasta em IoT e Desenvolvimento de Software, com foco em inovação tecnológica.

References🔗

Share article