This works:
/* This code is used to control a 12 volt DC water valve on my RV using a Mosfet.
The purpose is to automaticly turn the water supply off when it is not needed.
A Mosfet is used to switch the 12 volt ground on the valve.
D5 is is used to control the Mosfet as an OUTPUT.
A pushbutton is used to reset the countdown timer.
When pushed, it applies 3.3 volts D1, doing so sets the countdown timer value to 900000.
With each push of the pushbutton, the counter time is reset to 900000 and the countdown starts over again.
Anytime the countdown value is greater than 1, the code sends a HIGH signal out D5 to the Mosfet.
If the countdown value is less than zero, D5 is switched LOW turning the valve off.
NOTE: The value of the countdown timer is set to 900000 milliseconds at boot up, just in case the NodeMCU resets during a shower.
Serial Print is used to test operation.
Feel free to pass this code on to anyone and modify it as needed.
NOTE: I'm using a pull down resister between D1 and ground.
Connect any number of pushbuttons between D1 and any 3.3 volt on the NodeMCU.
*/
int PushButtonState = 0; // variable for reading the pushbutton status
int TimeLeft = 900000; //sets on time to 15 minutes on boot up in case it reboots during shower
int MinutesLeft = 0;
void setup() {
// initialize pins
pinMode(D5, OUTPUT);
pinMode(D1, INPUT);
Serial.begin(9600);
}
void loop() {
PushButtonState = digitalRead(D1); // reads the state of the PushButton value:
if (PushButtonState == HIGH) {
(TimeLeft = 900000); // resets on time to 15 minutes with push of button
}
if (TimeLeft 1) {
digitalWrite(D5, HIGH); // sets D5 HIGH
TimeLeft = TimeLeft - 28; // I played with this # util the time was really close to 15 minutes
delay(10);
MinutesLeft = TimeLeft / 60000; // Calculates minutes based upon milliseconds left
Serial.print("Minutes Until Shut Off: ");
Serial.println( MinutesLeft);
}
}