1
0
Fork 0

Initial Commit

master
Ambrose Chua 2016-07-31 23:50:10 +08:00
commit 693ed9806b
4 changed files with 83 additions and 0 deletions

37
CapacitiveButton.cpp Normal file
View File

@ -0,0 +1,37 @@
#include "CapacitiveButton.h"
// This is a fast capacitive touch library that aims to have low response time for activation
CapacitiveButton::CapacitiveButton(uint8_t sendPin, uint8_t receivePin, uint16_t nthreshold) : sensor(sendPin, receivePin) {
threshold = nthreshold;
}
bool CapacitiveButton::getState() {
return state;
}
uint16_t CapacitiveButton::getRaw() {
return average;
}
bool CapacitiveButton::update() {
uint16_t reading = sensor.capacitiveSensor(1);
uint16_t last_cycletime = millis() - last_time;
last_cycletime += last_cycletime ? 0 : 1; // prevent divide by zero
last_time = millis();
// average = (reading + average * SMOOTHING_CYCLES) / (SMOOTHING_CYCLES + 1);
float cycletime_factor = SMOOTHING_TIME / (float) last_cycletime;
average = (reading + average * cycletime_factor) / (cycletime_factor + 1);
if (state != (average > threshold)) { // if state of button has changed
if (!state) { // if new state is active
average += TIMEOUT_FACTOR * threshold;
state = true;
}
else {
state = false;
}
return true;
}
return false;
}

20
CapacitiveButton.h Normal file
View File

@ -0,0 +1,20 @@
#include <CapacitiveSensor.h>
//#define SMOOTHING_CYCLES 10 // increase to reduce activation errors
#define SMOOTHING_TIME 16 // smoothing time in milliseconds
#define TIMEOUT_FACTOR 100 // increase to 600 for reduced repeated touches
class CapacitiveButton {
public:
CapacitiveButton(uint8_t sendPin, uint8_t receivePin, uint16_t threshold = 40);
bool getState();
uint16_t getRaw();
bool update(); // returns true when state has changed
private:
CapacitiveSensor sensor;
uint16_t threshold = 40;
bool state = false;
uint16_t average = 0;
uint16_t last_time = 0;
};

View File

@ -0,0 +1,17 @@
#include "CapacitiveButton.h"
CapacitiveButton btn1 = CapacitiveButton(2, 5);
CapacitiveButton btn2 = CapacitiveButton(2, 6);
void setup() {
Serial.begin(9600);
}
void loop() {
if (btn1.update() || btn2.update()) {
Serial.print(btn1.getState());
Serial.print("\t");
Serial.println(btn2.getState());
}
delay(1); // if the looptime is less than one ms, fluctuations will be more sensetive
}

9
library.properties Normal file
View File

@ -0,0 +1,9 @@
name=CapacitiveButton
version=0.0.1
author=Ambrose Chua
maintainer=Ambrose Chua
sentence=CapacitiveSensor wrapper for capacitive buttons.
paragraph=CapacitiveButton is a small wrapper around CapacitiveSensor that filters the raw capacitive sensor data for use as a button. Requires CapacitiveSensor to be installed.
category=Sensors
url=http://playground.arduino.cc/Main/CapacitiveSensor
architectures=*