Problem creating timer program to cycle on/off every 2 hours

Hello. Here is my code:

void setup() {
  // put your setup code here, to run once:


  pinMode(12, OUTPUT);
  unsigned long outPin = 12;

}

void loop() {
  // put your main code here, to run repeatedly:
  unsigned long outPin = 12;
  digitalWrite(outPin, HIGH);
  delay(4000);
  digitalWrite(outPin, LOW);
  delay(2 * 60 * 60 * 1000);

}

I am using an uno connecting pin 12 to a transistor, which turns on a 5v relay which controls a 120v AC pump. The pump turns on initially and off after the first delay of 4 seconds. The 2nd delay is supposed to keep it off for 2 hours. However, the pump does not come back on after the 2 hours. When trouble shooting, the code works fine when set to short times. I made the 2nd delay (222*1000) and the pump turned on for 4 seconds, and off for the expected 8 seconds, then repeats. I read there are problems with the "delay" function, but the "millis" function looked to complicated for me to figure out. Any help would be appreciated.

The problem is the default integer multiplication on AVR based Arduinos, which overflows at 32767.

The fix is to use unsigned long variables and constants with times.

  delay(2UL * 60 * 60 * 1000);

But you really should avoid using delay(). Study the Blink Without Delay example to learn how.

Here you go.

#include "blinker.h"

// So everyone wants newbies to write blink without delay. This is good
// because delay() is bad. Well, here's the simple way to do it..

// Allocate a global blinker object.
blinker aBLinker(12,4000,2.0 * 60.0 * 60.0 * 1000.0);             

void setup() {

   // Fire it up.
   aBLinker.setOnOff(true);   
}


void loop() {

   // blinker is an idler. Calling idle() once in loop lets ALL idlers run.
   idle();                    
}

Install LC_baseTools from the library manager to compile this.

-jim lee

Try this code

#include <millisDelay.h>
// millisDelay is in the SafeString library, install from the Arduino Library manager
// see millisDelay tutorial  https://www.forward.com.au/pfod/ArduinoProgramming/TimingDelaysInArduino.html

millisDelay outHighDelay;
const unsigned long HIGH_DELAY_MS = 4000;

millisDelay outLowDelay;
const unsigned long LOW_DELAY_MS = 2ul * 60 * 60 * 1000;
const int outPin = 12;

void setup() {
  pinMode(12, OUTPUT);
  digitalWrite(outPin, HIGH);
  outHighDelay.start(HIGH_DELAY_MS);
}

void loop() {
  if (outHighDelay.justFinished()) {
    digitalWrite(outPin, LOW);
    outLowDelay.start(LOW_DELAY_MS);
  }
  if (outLowDelay.justFinished()) {
    digitalWrite(outPin, HIGH);
    outHighDelay.start(HIGH_DELAY_MS);
  }
}

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.