I have tried every variation of writing the code but did not get the outcome i desired. I came across this code in the forum that does exactly what I want but i can't seem to figure how it differed from what I came up with. The code is the following:
int ledPin = 13;
int buttonPin = 2;
int firsttime = 1;
unsigned long startTime;
unsigned long pressTime;
void setup()
{
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
digitalWrite(buttonPin, HIGH);
Serial.begin(9600);
}
void loop()
{
if(digitalRead(buttonPin) == LOW){
if(firsttime == 1){
startTime = millis();
firsttime=0;
}
pressTime = millis()- startTime;
if(pressTime >= 1){
Serial.print("Time: ");
Serial.print(pressTime);
Serial.print(" milliseconds ");
Serial.print(int(pressTime/1000));
Serial.println(" seconds");
}
if(pressTime>10000){
digitalWrite(ledPin, HIGH);
Serial.println("holding");
}
}
else if(firsttime == 0){
firsttime = 1;
Serial.println("Time: 0 milleseconds; 0 seconds");
digitalWrite(ledPin, LOW);
}
}
Can anyone explain to me what I was doing wrong compared to the code above (what is the purpose of frsttime variable)? Also if I wanted to apply the same loop to another button, would I need to repeat the code or is there a more efficient way to do that? And if anyone can also to tell me how i can display the Serial.println("holding") only once when the if statement is satisfied(If i used an lcd i don't want the print to appear continuously, but only once)
Thanks for your patience everyone.