I am new to Arduino programming. Let me describe the application I am working on. I am pressing a button for a certain period of time (30 sec). I can not hold it in a pressed position for all the time. I want to avoid accidental transition from button state going from logic HIGH to LOW. I am trying to drive a solenoid valve only at the end of the event.
The algorithm I am using is if once the system detects a HIGH from the sensor it goes in a loop and looks for transition to LOW. It checks if there is continuous LOW for more than 5 sec. If NO then it resets to start checking LOW again. If YES that means end of event and drives the solenoid valve.
The problem I am facing with the code is although the transition to LOW and remaining in LOW is less than 5 sec, the system is sending pulse to drive the solenoid valve. I have incorporated Serial.print() function to observe the value of the sensor input state and elapsed-time. The elapsed-time variable does not reset and keep increasing even though the button state reverts from LOW to HIGH.
I am incorporating part of the code here which is related to the algorithm. I will greatly appreciate if you kindly take a look at the code and the output file and help me detect the bug.
Thanks again! Niloy.
void loop() {
buttonstate = digitalRead(button); // read the state of the microswitch value: HIGH "on" or LOW "off"
if (buttonstate == HIGH ){
countstart = 1;
while(countstart == 1) {
buttonstate = digitalRead(button); // read the state of the microswitch value: HIGH "on" or LOW "off"
if ( ( buttonstate == LOW ) && ( startFlag == 0 ) ) { //start new time sequence
startFlag = 1;
startTime = millis();
}
if ( ( buttonstate == LOW ) && startFlag == 1 ){
endTime = millis();
elapsedTime = endTime - startTime;
}
if ( ( buttonstate == HIGH ) && startFlag == 1 ){
startFlag == 0;
endTime = startTime =0;
elapsedTime = endTime - startTime;
countstart = 0;
}
Serial.print(buttonstate);
Serial.print("\n"); // Print tab space
Serial.print(elapsedTime);
Serial.print("\n"); // Print tab space
if ( elapsedTime >= 5000)
{
delay(2000); //2 sec delay
solenoid->run(FORWARD);
delay(40);
solenoid->run(RELEASE);
delay(500);
solenoid->run(BACKWARD);
delay(40);
solenoid->run(RELEASE);
countstart = 0;
endTime = startTime =0;
elapsedTime = endTime - startTime;
buttonstate = LOW;
delay(15000); //wait for 15 sec
}
}
}
}