Instantly share code, notes, and snippets.

Embed
What would you like to do?
Capacitive Sensor
#include <CapacitiveSensor.h>
/*
CapitiveSense Library Demo Sketch
Paul Badger 2008
modified by Eric Forman 2017
Install library from Arduino IDE: Go to Sketch / Include Library / Manage Libraries, then search for "capacitiveSensor"
and select library by Paul Badger, Paul Stoffregen, select latest version, click Install.
Use a high value resistor (e.g. 10M, or 10 mega-ohm) between send pin and receive pin
Resistor effects sensitivity: experiment with values, 50K - 50M. Larger resistor values yield larger sensor values
Receive pin is the sensor pin - try different amounts of foil/metal on this pin
Best results are obtained if sensor foil and wire is covered with an insulator such as paper or plastic sheet
Determine the raw values of your sensor first, then adjust map() parameters
Optional: use a smoothing function after mapping
*/
CapacitiveSensor cs_4_2 = CapacitiveSensor(4, 2); // pin 4 is send pin: 10 megaohm resistor between pins 4 and 2
// pin 2 is receive/sensor pin: add wire, something metal
int ledPin = 9; // LED connected to digital pin 9
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop() {
// parameter is # of samples, i.e. sensor resoultion. Default 30.
// increase for higher res, but slower performance.
long sensorVal = cs_4_2.capacitiveSensor(50);
// debug raw sensor output value
Serial.print(sensorVal);
// map sensor value to LED PWM brightness 0-255 range
// (change "5, 5500" to the minimum, maximum raw values of your sensor)
sensorVal = map(sensorVal, 5, 5500, 0, 255);
// make sure value is between 0-255
sensorVal = constrain(sensorVal, 0, 255);
Serial.print("\t"); // print "tab" character
Serial.println(sensorVal); // print re-mapped value
// output LED with relative brightness:
analogWrite(ledPin, sensorVal);
delay(10); // arbitrary delay to limit data to serial port
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment