So you're a Noob? Post your questions here until you graduate! Don't be shy.
User avatar
By Ppl39
#71745 I'm writing code so I can control a water pump with the ESP8266 12e

The first code works while in the loop but I'll be adding more code as I figure things out and would like the loop to get the timer from a void. So why does the second code not work?

Code: Select allconst int pump = 4;
unsigned int pumpOnTime = 1;
unsigned int pumpOffTime = 2;
int pumpPowerValue = 100;
unsigned long previousMillis = 0;
unsigned long minutesPumpOn = pumpOnTime * 1000 * 60;
unsigned long minutesPumpOff = pumpOffTime * 1000 * 60;
int interval = pumpOnTime;

boolean pumpOnOffToggle = true;


void setup() {
  pinMode(pump, OUTPUT);
  analogWrite(pump, pumpPowerValue);
}

void loop() {


  unsigned long currentMillis = millis();


  if ((unsigned long)(currentMillis - previousMillis) >= interval) {

    if (pumpOnOffToggle) {
      analogWrite (pump, 0);
      interval = minutesPumpOff;
    } else {
      analogWrite (pump, pumpPowerValue);
      interval = minutesPumpOn;
    }

    pumpOnOffToggle = !(pumpOnOffToggle);


    previousMillis = currentMillis;
  }
}


Code: Select allconst int pump = 4;
unsigned int pumpOnTime = 1;
unsigned int pumpOffTime = 2;
int pumpPowerValue = 100;
unsigned long previousMillis = 0;
unsigned long minutesPumpOn = pumpOnTime * 1000 * 60;
unsigned long minutesPumpOff = pumpOffTime * 1000 * 60;
int interval = pumpOnTime;

boolean pumpOnOffToggle = true;


void setup() {
  pinMode(pump, OUTPUT);
  analogWrite(pump, pumpPowerValue);
}

void loop(){
  pumpTimer;
}

void pumpTimer()
{

  unsigned long currentMillis = millis();


  if ((unsigned long)(currentMillis - previousMillis) >= interval) {

    if (pumpOnOffToggle) {
      analogWrite (pump, 0);
      interval = minutesPumpOff;
    } else {
      analogWrite (pump, pumpPowerValue);
      interval = minutesPumpOn;
    }

    pumpOnOffToggle = !(pumpOnOffToggle);


    previousMillis = currentMillis;
  }
}