Relay won't turn off. Help?

Hello,
I got this code to run a pump for certain seconds and the challenge is that if the wateringTime is more than about 32 seconds, the relay won't stop anymore. Under 30 seconds working time it works fine. How can I make it work even when wateringTime is more then 32 seconds?

const int pump = 2;      // pump relay pin
int wateringTime = 3;    // For how many seconds you need your pump to remain on

// Convert seconds to minutes and hours
int seconds = 1000L;
unsigned long minutes = seconds * 60;
const unsigned long lcdOnPeriod = 16000;

void setup() {
  Serial.begin(115200);
  pinMode(pump, OUTPUT);
}

void loop() {
      digitalWrite(pump, HIGH);
      delay(wateringTime * seconds);
      digitalWrite(pump, LOW);
}

wateringtime is an INT...

minutes is seconds / 60 not x 60

The type int, on most kinds of arduino, is 16 bits, so can only hold numbers up to about 32,000, which is 32 seconds expressed in milliseconds.

When this multiplication gets done, both numbers are int, so the result is also an int and can only hold numbers up to around 32,000. The fact that you said 1000L does not fix the problem because it gets assigned to a variable that is an int.

So all you need to to is change it like this:

long seconds = 1000L;

Even better would be

const unsigned long seconds = 1000UL;
1 Like

It works for under 30 seconds. Because I have this line int seconds = 1000L; which converts the milliseconds to seconds. But I don't know why it doesn't work for longer periods of time, like 45 seconds.

> on
> wait
> off
> on
> loop

How long is it supposed to be off ?

Because when you multiply an int by an int the compiler returns an int and an int can only support 32.767 seconds. I recommend the following changes along with what @lastchancename alluded to.

const int pump = 2;      // pump relay pin
const unsigned long wateringTime = 3;    // For how many seconds you need your pump to remain on

// Convert seconds to minutes and hours
const unsigned long seconds = 1000L;
const unsigned long minutes = seconds * 60;
const unsigned long lcdOnPeriod = 16000;

void setup() {
  Serial.begin(115200);
  pinMode(pump, OUTPUT);
}

void loop() {
      digitalWrite(pump, HIGH);
      delay(wateringTime * seconds);
      digitalWrite(pump, LOW);
      // TBD: you need a delay here for off time
}

OMG! It works! And I learned something new. Thank you so much Paul!

1 Like

Numeric Overflow

The real reason your relay won't turn off is the reason @lastchancename said. After the delay, digitalWrite() switches the relay off, but then loop() starts over and switches the relay back on again. The relay is off for such a tiny period of time that it's electromagnet and switch contacts don't have enough time to respond, so it stays on.

1 Like

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