Capacitive Sensor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 | |
This code sends both the raw value and the mapped value to the serial port for debugging, but likely | |
you will only want to send one or the other | |
*/ | |
// pin 4 is the send pin: 10 megaohm resistor between pins 4 and 2 | |
// pin 2 is the receive pin: connect sensor (something metal) | |
CapacitiveSensor cs_4_2 = CapacitiveSensor(4, 2); | |
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