How to add timer to relay sketch??

Hi i am pretty sure that this is a fairly simple task, however i am finding it very difficult to work out actually what code to write in the sketch.
Can someone please help me??

I have a relay sketch that operates 4 relays. It runs a webserver that gives me a web page with 4 buttons to switch each relay. Once i have activated the relay by pressing the ON button I would like a timer to automatically turn off the relay after 10 minutes. When i press the OFF button i would like it to overide the timer and deactivate the relay.

Here is my sketch so far, please can you show me where to add the timer code and basically how to write it, many thanks!!!:

I have attached the .ino file

relay_4.ino (9.42 KB)

i am finding it very difficult to work out actually what code to write in the sketch.

This is really vague. Can you narrow it down ? Obviously you didn’t just start programming yesterday so you must know something. In the interest of saving us time can you tell us what part of your code is not working properly ?
I see you are using serial prints to diagnose the operation so what are they telling you ?
What do you need help with ? The 10 minutes turn off is trivial (see attached sketch which incorporates a 10 second count down timer to turn off the backlight of the lcd. All you have to do is do the math to make it 10 MINUTES.

So what else do you need help with ?

Backlight_Delayed_TurnOFF.ino (2.49 KB)

You almost certainly need to use millis() and the technique in the Blink Without Delay example sketch to control the time. Several things at a time is an extended demo of the technique.

...R

do tell .... XD

Hi, thank you very much for your responses! OK to go into a little more detail. The four relays are basically going to control 4 solenoid valves that control 4 zones in my garden for watering purposes. There are irrigation programs out there however they don't seem to compile without hundred as of errors and I haven't got the skills in programming to sort them all out. For my project I want to keep things simple! A simple webserver that I can log into and control each zone by the press of a button. The running of the webserver is not a problwm , and it all works with 4 buttons that I press which operate each individual relay. The problem I am having is where to put timer code in my sketch so that when I turn on the zone it will stay on for a predetermined amount of time I.e. 10mins. Then if before the 10 minutes is UPI want to turn off the zone I can press the OFF button to stop it. I'm sure that this is pretty simple but I just need a hint or example that shows where in the sketch it should be written. Hope this helps :slight_smile:

I assume its that part of the garagesensor.ino that relates to my problem:

// Backlight on - ten seconds - then off again
int blpinStatus = 0;
blpinStatus = digitalRead(blpin);
static unsigned long blTime;
static boolean blOn;

if (blpinStatus == LOW)
{
delay(20); // Debounce
blOn = true;
blTime = millis();
lcd.backlight();
}
if (blOn == true && millis() - blTime > 10000)
{
lcd.noBacklight();
blOn = false;
}
}

But where would I put this code?? Would it be in every section that relates to the ON button?? Would this allow me to stop the process if I wanted to by pressing the off button. If someone could look at the original code I attached and put what they think I should include to make this work and repost it would help me understand a lot easier. Many thanks

If you look at the several things at a time link that I posted earlier you will see how that uses millis(). You just need to use relays instead of leds and adjust the timing.

If there is something about it you don't understand I will try to help.

...R

Hi robin, really appreciate the reply. What i dont understand is what part of that script do i insert into mine? Obviously i want to continue to use my script as it has the webserver and relays all set up, i just want to extract the part that will turn each relay off after the period of time. Sorry to be a pain but pretty new to a lot of this.

i assume that i need to put the timer code somewhere within the code for each button when pressed
for example somewhere in here??? and then repeat for each button. Am i correct?? Please take a look at my original code and let me know what you think.

if(readString.indexOf("?relay1on") >0)//checks for on

{

digitalWrite(4, HIGH); // set pin 4 high

Serial.println(“Led On”);

client.println("");

//client.println(“Light 1 Is On”);

client.println("
");

}

else{

if(readString.indexOf("?relay1off") >0)//checks for off

{

digitalWrite(4, LOW); // set pin 4 low

Serial.println(“Led Off”);

client.println("");

//client.println(“Light 1 Is Off”);

client.println("
");

Someone please show the OP kow to use code tags.
("#") toolbtton.

if(readString.indexOf("?relay1on") >0)//checks for on

          {

            digitalWrite(4, HIGH); // set pin 4 high

            Serial.println("Led On");

            client.println("<link rel='apple-touch-icon' href='http://chriscosma.co.cc/on.png' />");

            //client.println("Light 1 Is On");

            client.println("
");

        }

          else{

          if(readString.indexOf("?relay1off") >0)//checks for off

          {

            digitalWrite(4, LOW); // set pin 4 low

            Serial.println("Led Off");

            client.println("<link rel='apple-touch-icon' href='http://chriscosma.co.cc/off.png' />");

            //client.println("Light 1 Is Off");

            client.println("
");

lol at least i worked something out today for myself!!! Thanks Raschemmel!!

   // Backlight on - ten seconds - then off again   
    int blpinStatus = 0;
    blpinStatus = digitalRead(blpin);
    static unsigned long blTime;
    static boolean blOn;
    
    if (blpinStatus == LOW) 
    {
      delay(20);        // Debounce
      blOn = true;
      blTime = millis();
      lcd.backlight();
     } 
    if (blOn == true && millis() - blTime > 10000)
    {
      lcd.noBacklight();
      blOn = false;
    }
}

Take another look at this code.
You already know this sketch is written for a 10 SECOND delay. You want 10 MINUTES.
As you recall, I said DO THE MATH. How many milliseconds in 10 MINUTES ?
10 Min * 60 sec/min * 1000 mS /sec =600000.
Can this value be expressed with an 8-bit variable type (no)
Can this value be expressed with a 16-bit variable type (yes)
So you need to change the variable names and types to names that appropriate for your application and change the variable type to unsigned long and where you see the value "10000" in that sketch, it should have been defined as a constant instead of hardcoded as "10000", which is poor practice. Define it as a constant. Assign it the value 600000.
Change this :

 if (blpinStatus == LOW)

to a conditional that makes sense for your application.
Change the name of the boolean blOn to something appropriate for your application.
change the name of this:
  blTime  to something appropriate for your application.
Change the name of this:

blpinStatus

to something appropriate for your application.
Change this:

  lcd.backlight();

and this:

   lcd.noBacklight();

to what you want to happen in your code.
This sketch turns OFF the backlight in 10 seconds so it starts with this:

  lcd.backlight();

and changes to this;

   lcd.noBacklight();

Think about what you want to happen and change this code accordingly. I'm not going to do it for you because this forum exists to help you learn, not to do your work for you. We can only take it so far (normally, although we have been known to make exceptions when people cook up a really good song & dance story to get our sympathy, (My 95 yr old grandmother is all alone and needs etc etc etc..)

Sorry i think i am making a hash of this. I understand the 600000 part but i do not understand what i need to put to make the other changes. I appreciate that you do not want to do the work for me. I am willing to learn, however sometimes you need to see the answer to make sense of it all and to be able to see what is going on. Here is the code that i have attempted to change, as you will see its not any good!!! PS, i thought I HAD mentioned this was for my grannies garden that she struggles to water now!!! :wink:

// relay on - ten minutes - then off again   
    int blpinStatus = 0;
    blpinStatus = digitalWrite(4, HIGH);
    static unsigned long relayTime;
    static boolean blOn;
    
    if(readString.indexOf("?relay4off") >0) 
    {
      delay(20);        // Debounce
      blOn = true;
      relayTime = millis();
      lcd.backlight();
     } 
    if (blOn == true && millis() - relayTime > 600000)
    {
      lcd.noBacklight();
      blOn = false;
    }
}

i thought I HAD mentioned this was for my grannies garden that she struggles to water now!!! smiley-wink

ha , ha , ha. XD

Here is the code that i have attempted to change, as you will see its not any good!!!

First of all, I assumed you realized that the code posted in my last post was just a snippet from the sketch I uploaded previously (garagesensor). I know that sketch works and others have used it as an example to create countdown or up timers. Secondly, reread my last post. I specifically said to rename the variables to something relevant to your application. Which you have not done. I’m trying to help you but I require your cooperation. If I tell you to do something, do it. If you cannot follow instructions, do it yourself. I am not being rude. I am laying down the rules. This code you are asking for is not a single line. Everything has to occur in steps. The first step is define your variables. You should know that. You cannot write code until you have done that. Your application does not involve a backlit lcd so you couldn’t possibly run that code and tell me if it works or not. Telling me your modication to a sketch that controls a device you don’t even possess is “no good” is absurd. There is no code in their for controlling a relay and this line:

   if(readString.indexOf("?relay4off") >0)

doesn’t belong here.

//==============================================
blpinStatus : this is variable used to indicate whether or not the user has pressed a pushbutton to turn on the backlight (which would start the 10 second countdown) You don’t have a pushbutton so you need to tell your program that you are starting the timer. Simply turning on the relay does not provide any input to the timer code. You need a boolean (or integer) variable that denotes the starting of of the countdown timer . ie:

 int starttimer=0;

static unsigned long blTime; //You don’t have a backlight so it makes no sense to have a variable named blTime. Obviously this needs
to be changed to either relay_time or relay4_time. You decide.
static boolean blOn; // This is boolean that denotes the state of the backlight but unlike the blStatus, it does not indicate a switch
press, it indicates the status and of the backlight , not of any switch pin. Just to be clear, if you want to know the state of the backlight you could use some kind of hardware feedback, like a light sensor or measure the voltage on the current limiting resistor for the backlight. But since there was no need for that when this sketch was written, the status was monitored by using a boolean flag that was set when the backlight was turned on and cleared when it was turned off. You need to do the same thing for all four relays, which means the name of this flag should be relay4_on, or relay_on. You decide.
if (blpinStatus == LOW) // can’t discuss this line because you haven’t changed the variable name yet.
{
delay(20); // Debounce (you don’t have a switch so there is nothing to debounce

blOn = true; // can’t discuss this line because you haven’t changed the variable name yet.

blTime = millis(); // can’t discuss this line because you haven’t changed the variable name yet.

lcd.backlight(); // Can you guess what belongs here ?
}
if (blOn == true && millis() - blTime > 10000) // Can you guess what belongs here ?
{
lcd.noBacklight(); // Can you guess what belongs here ?
blOn = false; // // Can you guess what belongs here ?
}
}

//==============================================

Change the variable names as you were instructed and we can proceed …

This is the snippet we will modify as an example once you have changed the variablenames in the snippet I uploaded in my last post.
We will take that code and put it in the following code.

         if(readString.indexOf("?relay1on") >0)//checks for on

          {

            digitalWrite(4, HIGH); // set pin 4 high

            Serial.println("Led On");

            client.println("<link rel='apple-touch-icon' href='http://chriscosma.co.cc/on.png' />");

            //client.println("Light 1 Is On");

            client.println("
");

        }

          else{

          if(readString.indexOf("?relay1off") >0)//checks for off

          {

            digitalWrite(4, LOW); // set pin 4 low

            Serial.println("Led Off");

            client.println("<link rel='apple-touch-icon' href='http://chriscosma.co.cc/off.png' />");

            //client.println("Light 1 Is Off");

            client.println("
");

        }

Just for the record, in case it has not occurred to you, when you post on this forum , there is more going on that just the project that you are posting for. This is a help forum. If you everyone were only allowed one post per lifetime then there would be no need to train them on how to use this forum. Obviously that is not the case. So when you post about a project to build a watering timer for your grandma, you are also learning how to use this forum so you won’t waste our time and force us to play 20 questions next time. Part of this learning process is you understanding that we are not psychic and cannot read your mind. When you say you can’t do something or don’t understand something, we don’t know why so it makes it very difficult for us to help you. When I post an example sketch that contains variables you don’t understand, you are supposed to ask what they mean.
ie:
What is "blstatus " for ?
etc…
There is no point in plugging code from your sketch into a sketch that has variable names that have nothing at all to do with your sketch. You were asked to changed the names and didn’t. Skipping that step is not shortening the solution for you. It is only making it longer because I am forced to ask you again. This will go on forever until it is done. We cannot skip that step any more than you could skip that step when you wrote your sketch. In short, when you post for the first time there are many things you need to know:
Most if not all of them are listed here:
http://forum.arduino.cc/index.php/topic,148850.0.html

In a nutshell it says :
1-Present ALL the necessary information on your first post (code, schematics , photos, etc)
2- If you don’t understand a reply, ASK QUESTIONS
3- If you are asked to do something , do it, or give a good reason why you cannot.

FYI,
Just for the record, software is not my area of expertise. My specialty is hardware. I am doing the best I can with my limited programming skills but I understand the basics, (like declaring variables with appropriate names BEFORE modifying code).
Robin is probably better suited to help you but the last time I said “Robin can help you” he didn’t appreciate me dumping the whole mess on his plate and running off …so I will just say, if you don’t find my input helpful , just say so and I’ll bail…

Hi, I didn't mean to cause any offence, I think you misunderstood when i said the code was no good. I was referring to what I had done, it wasn't any good, not that your code wasnt any good! I appreciation your patience however I am new to this. I didn't realise that this would be such a difficult task. The original code i posted is my entire sketch, I thought a simple timer to keep a relay on for ten minutes would be easy. I just neeed to know where about to put it in the sketch. Maybe by marking on my sketch in red or something would point out where I would need to add it. As far a variables it might be easier for me if you refer it back to my sketch, this is what confuses me. In my sketch all I use is digital write to make the pins high or low. I will try and work out what you have suggested but I will probably need to ask a lot more questions. Sorry.

As far a variables it might be easier for me if you refer it back to my sketch, this is what confuses me.

Reply#13

If you don't understand a reply, ASK QUESTIONS

BTW,
I just realized that a 16-bit variable is only good to 65535 so it is not going to work for a count of 600,000 milliseconds. For that you will need a unsigned double integer. which if I cam correct, should be good to 4294967296 milliseconds. Since there are 86400000 milliseconds in one day, the maximum time for any count up or count down timer is 49 days.