// Capacitive sensor switch // Sun 2013 Jan 27 15:23 Kevin Karplus // To use, connect the output of the hysteresis oscillator to // pin CAP_PIN (default is digital pin 2) on the Arduino. // The code turns on the LED on pin 13 when a touch is sensed. // The Arduino measures the width of one LOW pulse on pin CAP_PIN. // The LED is turned on if the pulse width is more than high_pulse_usec // The LED is turned off if the pulse width is less than low_pulse_usec // The LED state is unchanged if the pulse width is between these // pin that oscillator output connected to #define CAP_PIN (2) // Two thresholds for detecting touch by change in period of oscillator // The initial values here are not used---the values are automatically // set when the Arduino is reset. // The sensor should not be touched until the LED is flashed 3 times, // to indicate that the automatic sensing is done. static uint16_t low_pulse_usec=40; static uint16_t high_pulse_usec=50; void setup(void) { pinMode(CAP_PIN,INPUT); pinMode(13, OUTPUT); digitalWrite(13, 0); // Assuming that the touch sensor is not touched when resetting, // find the maximum typical value for untouched sensor, // and use this for the lower threshold. low_pulse_usec=1; uint32_t start_time=millis(); while (millis()-start_time < 300) { uint32_t pulse=pulseIn(CAP_PIN,LOW); if (pulse>low_pulse_usec) { low_pulse_usec =pulse; } } low_pulse_usec += 1; // add some room for noise // Set the high threshold for detecting the pulse at 20% longer low time high_pulse_usec = 12*low_pulse_usec/10; // flash the LED three times to indicate that the board is ready digitalWrite(13, 0); delay(100); digitalWrite(13, 1); delay(100); digitalWrite(13, 0); delay(100); digitalWrite(13, 1); delay(100); digitalWrite(13, 0); delay(100); digitalWrite(13, 1); delay(100); digitalWrite(13, 0); delay(100); } void loop(void) { // Measure the pulse width from the hysteresis oscillator uint32_t pulse_width= pulseIn(CAP_PIN,LOW); if (pulse_width>= high_pulse_usec) { // pulse is long enough to turn LED on digitalWrite(13, 1); // wait, to make sure LED stays on for 1/5 second delay(200); } else if (pulse_width<= low_pulse_usec) { // pulse is short enough to turn LED off digitalWrite(13,0); // wait, to make sure LED stays off for 1/5 second delay(200); } }