Simplest capacitive touch implementation

Dependencies:   mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

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 }