I am creating a diy capacitive switch using aluminum foil that turns on/off led when the switch is touched slightly, and changes the brightness of the led when its touched and held. But it's just not working and I don't know where it has gone wrong. Can somebody tell me where it has gone wrong and provide me a solution for this?
int capSensePin = 3; // pin connected to alunmium foil
int ledPin = 13;
int touchedCutoff = 100;
bool ledState = false;
unsigned long touchStartTime = 0;
int brightness = 0;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(capSensePin, INPUT);
}
void loop() {
if (readCapacitivePin(capSensePin) > touchedCutoff) {
if (!ledState) {
ledState = true;
touchStartTime = millis();
} else {
unsigned long touchDuration = millis() - touchStartTime;
if (touchDuration < 1000) {
ledState = false;
digitalWrite(ledPin, LOW);
} else {
brightness += 10;
if (brightness > 255) {
brightness = 0;
}
analogWrite(ledPin, brightness);
while (readCapacitivePin(capSensePin) > touchedCutoff) {
delay(50);
}
}
}
} else {
if (ledState) {
unsigned long touchDuration = millis() - touchStartTime;
if (touchDuration > 1000) {
while (readCapacitivePin(capSensePin) <= touchedCutoff) {
delay(50);
}
}
}
}
}
uint8_t readCapacitivePin(int pinToMeasure){
volatile uint8_t* port;
volatile uint8_t* ddr;
volatile uint8_t* pin;
byte bitmask;
if ((pinToMeasure >= 0) && (pinToMeasure <= 7)){
port = &PORTD;
ddr = &DDRD;
bitmask = 1 << pinToMeasure;
pin = &PIND;
}
if ((pinToMeasure > 7) && (pinToMeasure <= 13)){
port = &PORTB;
ddr = &DDRB;
bitmask = 1 << (pinToMeasure - 8);
pin = &PINB;
}
if ((pinToMeasure > 13) && (pinToMeasure <= 19)){
port = &PORTC;
ddr = &DDRC;
bitmask = 1 << (pinToMeasure - 13);
pin = &PINC;
}
*port &= ~(bitmask);
*ddr |= bitmask;
delay(0);
*ddr &= ~(bitmask);
int cycles = 16000;
for(int i = 0; i < cycles; i++){
if (*pin & bitmask){
cycles = i;
break;
}
}
*port &= ~(bitmask);
*ddr |= bitmask;
return cycles;
}