Using Adruino as a timer to control a relay- Problem

I'm trying to use the adruino uno to control a timer,
Basically, I am trying to control a relay. On 3 minutes, off 30 minutes. To continue this cycle indefinitely.

With my code, It works at first( the first cycle) and then randomly it switches itself to 3 minutes off and 30 minutes on, and then switches back. Sometimes it doesn't even come on at all.

Keep in mind, i am a noob with this, I have worked on it for days with trying to learn the proper way to code this. Realistically this is my only need right now with the adruino. ( well the ability to change the on/off times accordingly)

Here is what i'm using, I found it somewhere on one of the adruino forum posts.

int ledPin = 7;
int ledState = LOW;
unsigned long previousMillis = 0;
long OnTime = 120000;
long OffTime = 1800000;

void setup()
// set the digital pin as output:
pinMode(ledPin, OUTPUT);

void loop()
unsigned long currentMillis = millis();

if((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
ledState = LOW; // Turn it off
previousMillis = currentMillis;
digitalWrite(ledPin, ledState);
else if ((ledState == LOW) && (currentMillis - previousMillis >= OffTime))
ledState = HIGH; // turn it on
previousMillis = currentMillis;
digitalWrite(ledPin, ledState);

Does it make any difference if You use unsigned long for the limits, OnTime and OffTime?

long OnTime = 120000;

That’s 2 minutes, not 3.

It’s easier to keep things straight if you let the compiler do the math for you:

unsigned long OnTime = 3UL * 60UL * 1000UL;  // 3 minutes in milliseconds

I don’t see any glaring errors but it is best to used ‘unsigned long’ types for variables and constants used with millis().

What happens if you remove the ELSE ? (Not the whole line, just that word)


Welcome to the forum.

Please read the first post in any forum entitled how to use this forum.,148850.0.html then look down to item #7 about how to post your code.
It will be formatted in a scrolling window that makes it easier to read.

Can you please post a copy of your circuit, in CAD or a picture of a hand drawn circuit in jpg, png?

How are you controlling the relay and what is the relay switching? AC, DC, 110V or 240V, load current?

Does it work properly if you remove the relay and or the load it is switching?

Thanks… Tom… :slight_smile: