Millis not lasting longer than 6 seconds [solved]

Hi I’m trying to use the spark to control a relay based on the value of my sensor and turn it on for 20 seconds then off again. However, the relay doesn’t seem to be able to stay on longer than 6 seconds. Not sure if it is my code or due to power issues but I’m new to coding so would appreciate some help. Thanks. Here is part of my code.

bool relay = HIGH;
bool iswateron = LOW;
unsigned long water_timer;

if (sensorValue >= 301)
{
}

else if (sensorValue <= 300)
{
   relay = !relay; 
   digitalWrite(D5,relay); 
                
   iswateron = HIGH;
 } 

if (iswateron == HIGH)
{                
        water_timer = millis();                    
                    
        if (water_timer >= 20000)
        {
            relay = !relay; 
            digitalWrite(D5,relay);

            iswateron = LOW;
            
            water_timer = 0;
        }                    
}

I’ve edited your post to properly format the code. Please check out this post, so you know how to do this yourself in the future. Thanks in advance! ~Jordy

I think you might try smth like this:
if(water_timer + 20000 >= millis()) {

Hi thanks for the advice but i discovered that the issue lies somewhere else in my code :smile:

but you still have an issue here:

if (iswateron == HIGH)
    {
            water_timer = millis();
            if (water_timer >= 20000)
            {
                relay = !relay; 
                digitalWrite(D5,relay);
                iswateron = LOW;
                water_timer = 0;
            }
    }

@qwerty009 was onto something but you should take advantage of using Unsigned Long subtraction to avoid potential issues with millis( ) rolling over:

something like this:

if (iswateron == HIGH)
    {
            if (water_timer - millis( ) >= 20000)
            {
                relay = !relay; 
                digitalWrite(D5,relay);
                iswateron = LOW;
                water_timer = millis( );
            }
    }

millis( ) is a counter that begins when the MCU is started, so setting water_timer to equal millis( ) will make this true forever

water_timer = millis();
if (water_timer >= 20000)

once 20sec of uptime is achieved

1 Like