I'm using the CapacitiveSensor (Arduino Playground - HomePage) library in my project but I get some problem when writing a for loop. Here is my code:
#include <CapacitiveSensor.h>
CapacitiveSensor cs_2_4 = CapacitiveSensor(2,4); // 10M resistor between pins 4 & 2, pin 2 is sensor pin, add a wire and or foil if desired
int ledVal=0;
void setup()
{
Serial.begin(9600);
pinMode(12,INPUT); // pin 12 is connected to a pushbutton
pinMode(6,OUTPUT); // pin 6 is connected to a LED
}
void loop()
{
long start = millis();
long total1 = cs_2_4.capacitiveSensor(30);
Serial.print(millis() - start); // check on performance in milliseconds
Serial.print("\t"); // tab character for debug windown spacing
Serial.println(total1); // print sensor output 1
if(digitalRead(12)==HIGH && ledVal==0){ // puch the puchbutton turns the light on smoothly
for (ledVal=0;ledVal<1023;ledVal++){ analogWrite(6,ledVal); delay(5);}
Serial.println("trun on");
}
if(total1>100 && ledVal!=0){ // touch the capacitive sensor turns the light off smoothly
for(ledVal=1023;ledVal>0;ledVal--){ analogWrite(6,ledVal); delay(5);}
}
delay(100); // arbitrary delay to limit data to serial port
}
Function is simple: When the push button connected to the pin 12 is pushed, the led turns on and when the capacitive sensor is touched, the led turns off. I write a for loop to make the light changing smoothly. However, when running this project, the for loop always repeats four times - which means, when I activate the push button or the capacitive sensor, the light change on my led runs four times. Can somebody tell me where I did it wrong? Thanks!!