Hi All,
Firstly, I am new to the Arduino (bet you love hearing that!) and of course to the forum also...
I am trying to have my Uno control a peristaltic pump, the hardware bit I have sorted with a bit of YouTube and searching these forums, thanks for that!
What I would like it to do, and am struggling with, is if the button is just pressed to then run the pump for 5 seconds but if it is held, to then run for as long as the button is held.
I have got this to work, but there is a problem, two days of reading and trying things and now I am here asking for your help!
When the button is pressed and released it waits and then runs for 5 seconds, just as planned. If the button is held it waits and then runs for as long as its held, again just as planned. I can do this over and over again as much as I like and everything seems to be working just fine. However, if I hold the button and let it run for more than five or six seconds and release it, it does what it is suppose to but then after two seconds it starts the five second run unprompted by me.
I have found many threads on getting two different functions out of a button depending on the interaction with it, however I can't get them to run the pump for as long as it is held if it is held.
Below is the code I have so far, please excuse me if it appears a bit messy, it's been ripped apart and put back together more times than I care to think about.
const int buttonPin = 2;
const int pumpPin = 3;
unsigned long keyPressTime = 0;
unsigned long fillTime = 0;
int filling = LOW;
int keyPressed = LOW;
int longRun = LOW;
void setup() {
}
void loop() {
int currKeyState = digitalRead(buttonPin);
if ((keyPressed == LOW) && (longRun == LOW) && (filling == LOW) && (currKeyState == HIGH)) {
keyPressTime = millis();
keyPressed = HIGH;
}
if (((millis() - keyPressTime) > 2000) && (keyPressed) == HIGH) {
if (currKeyState == HIGH){
keyPressTime = millis();
analogWrite(pumpPin, 255);
longRun = HIGH;
} else if ((longRun == LOW) && filling == LOW) {
keyPressTime = millis();
analogWrite(pumpPin, 255);
filling = HIGH;
fillTime = millis();
}
}
if ((keyPressed == HIGH) && (currKeyState == LOW) && (filling == LOW) && (longRun == HIGH)) {
digitalWrite(pumpPin, LOW);
keyPressed = LOW;
longRun = LOW;
}
if (((millis() - fillTime) > 5000) && (filling == HIGH)) {
fillTime = 0;
digitalWrite(pumpPin, LOW);
keyPressed = LOW;
filling = LOW;
}
}
Any help is very much appreciated. As it is my first post please excuse me if I missed something out.
Many thanks!
Max
Edit: After more tinkering I noticed it is running the five second fill cycle when the top up cycle is held for LESS than two seconds (not more than five as stated above). This absolutely makes sense to me now as I have asked it do that in the code, if pressed for less than two seconds run the fill cycle, it just didn't occur to me! Now to stop it from doing that! Again any help is much appreciated!!!!