1#include <CapacitiveSensor.h>
2#include <stdio.h>
3#include <stdlib.h>
4
5CapacitiveSensor sensor[] = {
6 CapacitiveSensor(12, 2),
7 CapacitiveSensor(12, 3),
8 CapacitiveSensor(12, 4),
9 CapacitiveSensor(12, 5),
10 CapacitiveSensor(12, 6),
11 CapacitiveSensor(12, 7),
12 CapacitiveSensor(12, 8),
13 CapacitiveSensor(12, 9),
14 CapacitiveSensor(12, 10),
15 CapacitiveSensor(12, 11),
16};
17const int N_SENSORS = sizeof sensor / sizeof sensor[0];
18
19template <typename T> inline void swap(T &a, T &b) { T t = a; a = b; b = t; }
20
21long sensorBase[N_SENSORS]; // Floor values for sensors
22int lastBaseInc;
23
24void setup() {
25 Serial.begin(9600);
26 for (int i = 0; i < N_SENSORS; i++) {
27 sensor[i].set_CS_AutocaL_Millis(0xFFFFFFFF);
28 sensorBase[i] = 0x7FFFFFF0; // Avoid accidental wraparound
29 }
30 lastBaseInc = millis();
31}
32
33void loop() {
34 long result[N_SENSORS];
35 for (int i = 0; i < N_SENSORS; i++) {
36 const int N_SAMPLES = 5;
37 long samples[N_SAMPLES];
38 for (int j = 0; j < N_SAMPLES; j++)
39 samples[j] = sensor[i].capacitiveSensorRaw(5);
40 for (int j = 0; j < N_SAMPLES; j++)
41 for (int k = j + 1; k < N_SAMPLES; k++)
42 if (samples[j] > samples[k]) swap(samples[j], samples[k]);
43 result[i] = samples[N_SAMPLES / 2];
44 }
45
46 if (lastBaseInc + 1000 < millis()) {
47 for (int i = 0; i < N_SENSORS; i++) sensorBase[i]++;
48 lastBaseInc = millis();
49 }
50 for (int i = 0; i < N_SENSORS; i++) {
51 if (sensorBase[i] > result[i]) {
52 if (sensorBase[i] == 0x7FFFFFF0) sensorBase[i] = result[i];
53 else sensorBase[i]--;
54 }
55 result[i] -= sensorBase[i];
56 }
57
58 char line[N_SENSORS * 6 + 1];
59 for (int i = 0; i < N_SENSORS; i++)
60 sprintf(line + i * 6, "%5ld\t", result[i]);
61 Serial.println(line);
62}