Created
March 23, 2014 16:56
-
-
Save pral2a/9726000 to your computer and use it in GitHub Desktop.
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> | |
CapacitiveSensor capSensor = CapacitiveSensor(4,2); | |
const int numReadings = 10; | |
long readings[numReadings]; // the readings from the analog input | |
int index = 0; // the index of the current reading | |
long total = 0; // the running total | |
long average = 0; // the average | |
boolean isOn = false; | |
long prevTimeChanged = 0; | |
void setup() | |
{ | |
// initialize serial communication with computer: | |
Serial.begin(9600); | |
pinMode(13, OUTPUT); | |
// initialize all the readings to 0: | |
for (int thisReading = 0; thisReading < numReadings; thisReading++) | |
readings[thisReading] = 0; | |
} | |
void loop() { | |
// subtract the last reading: | |
total= total - readings[index]; | |
// read from the sensor: | |
readings[index] = capSensor.capacitiveSensor(300); | |
// add the reading to the total: | |
total= total + readings[index]; | |
// advance to the next position in the array: | |
index = index + 1; | |
// if we're at the end of the array... | |
if (index >= numReadings) | |
// ...wrap around to the beginning: | |
index = 0; | |
// calculate the average: | |
average = total / numReadings; | |
// send it to the computer as ASCII digits | |
Serial.println(average); | |
long currentTime = millis(); | |
if (average > 35.0 && (currentTime - prevTimeChanged > 2000)) { | |
prevTimeChanged = currentTime; | |
if (isOn) { | |
isOn = false; | |
digitalWrite(13, LOW); | |
} | |
else { | |
isOn = true; | |
digitalWrite(13, HIGH); | |
} | |
} | |
delay(1); // delay in between reads for stability | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment