Reworking on your code I second the suggestions @Computable posted in the comments section. I would leave the else
-block in and also delay the re-read in the if
-block to avoid polling the input too often. Try and refactor your code to this:
void setup() {
pinMode(9, OUTPUT);
pinMode(2, INPUT);
digitalWrite(9, false);
}
void loop() {
if(digitalRead(2)) {
digitalWrite(9, true); // activate pump
delay(3000); // let the pump run for 3s
digitalWrite(9, false); // deactivate pump
while(digitalRead(2)) { // wait until hand is no longer close to IR sensor
delay(.5 * 1000);
}
}
else {
digitalWrite(9, false); // deactivate pump
delay(.5 * 1000); // This avoids looping too often (re-read IR sensor only every 0.5 seconds)
}
}
Please share the results!