Simplest capacitive touch implementation

Dependencies:   mbed

Capacitive touch is widely used in our dairly life. Curious about how it works? Let's build a capacitive button.

/media/uploads/yihui/capacitive_touch.jpg

The capacitance of a capacitive button will be changed when with a human touch. There are several ways to measure the change of the capacitance. Here we use the charging/discharging time of a simple RC circuit to correlate the capacitance.

Hardware

  • An mbed board (Arch is used here)
  • An Apple with a bite
  • A wire

Use the wire to connect the Arch's P0_11 with the apple.

Software

The pull-down feature of a general porpuse I/O is used to discharging the capacitor of the touch button. A Ticker is used to measure the discharging time of the capacitor every 1/64 seconds.

Import program

00001 #include "mbed.h"
00002 
00003 DigitalOut led(LED1);
00004 DigitalInOut touch(P0_11);       // Connect a wire to P0_11
00005 Ticker tick;
00006 
00007 uint8_t touch_data = 0;         // data pool
00008 
00009 void detect(void)
00010 {
00011     uint8_t count = 0;
00012     touch.input();              // discharge the capacitor
00013     while (touch.read()) {
00014         count++;
00015         if (count > 4) {
00016             break;
00017         }
00018     }
00019     touch.output();
00020     touch.write(1);             // charge the capacitor
00021     
00022     if (count > 2) {
00023         touch_data = (touch_data << 1) + 1;
00024     } else {
00025         touch_data = (touch_data << 1);
00026     }
00027     
00028     if (touch_data == 0x01) {
00029         led = 1;                // touch
00030     } else if (touch_data == 0x80) {
00031         led = 0;                // release
00032     }
00033 }
00034 
00035 int main()
00036 {
00037     touch.mode(PullDown);
00038     touch.output();
00039     touch.write(1);
00040     
00041     tick.attach(detect, 1.0 / 64.0);
00042     
00043     while(1) {
00044         // do something
00045     }
00046 }

no such method: docs