How To Do Daily Tasks with Arduino

In this tutorial we’re going to show you how to perform daily tasks with the Arduino. We’re going to turn an LED on and off at a specific time of the day, everyday. You can then, easily modify the example provided to perform any other task.

Project overview

Parts required

For this example you need the following parts (click the links below to find the best price at Maker Advisor):

You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!

Schematic

Wire the DS1307 RTC module to the Arduino and the LED, as shown in the schematic below.

Build 25 cool Arduino projects with our course even with no prior experience DOWNLOAD »

Build 25 cool Arduino projects with our course even with no prior experience DOWNLOAD »

You can also refer to the following table to wire the DS1307 RTC module to the Arduino.

DS1307 RTC Module Pin Wiring to Arduino Uno
SCL A5
SDA A4
VCC 5V
GND GND

Installing libraries

For this example you need to install the following libraries: Time, TimeAlarms, and DS1307RTC created by Michael Margolis and maintained by Paul Stoffregen:

To install these libraries, in the Arduino IDE go to Sketch > Include Library > Manage Libraries. Then, enter the libraries’ name to install them.

Set DS1307 RTC module time

To set the DS1307 RTC module time, you need to upload the next sketch to your Arduino board and run it once:


/*
SetTime.ino sketch to set the time of DS1307 RTC - created by Paul Stoffregen
github.com/PaulStoffregen/DS1307RTC/blob/master/examples/SetTime/SetTime.ino
 */
 
#include <Wire.h>
#include <TimeLib.h>
#include <DS1307RTC.h>

const char *monthName[12] = {
  "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};

tmElements_t tm;

void setup() {
  bool parse=false;
  bool config=false;

  // get the date and time the compiler was run
  if (getDate(__DATE__) && getTime(__TIME__)) {
    parse = true;
    // and configure the RTC with this info
    if (RTC.write(tm)) {
      config = true;
    }
  }

  Serial.begin(9600);
  while (!Serial) ; // wait for Arduino Serial Monitor
  delay(200);
  if (parse && config) {
    Serial.print("DS1307 configured Time=");
    Serial.print(__TIME__);
    Serial.print(", Date=");
    Serial.println(__DATE__);
  } else if (parse) {
    Serial.println("DS1307 Communication Error :-{");
    Serial.println("Please check your circuitry");
  } else {
    Serial.print("Could not parse info from the compiler, Time=\"");
    Serial.print(__TIME__);
    Serial.print("\", Date=\"");
    Serial.print(__DATE__);
    Serial.println("\"");
  }
}

void loop() {
}

bool getTime(const char *str)
{
  int Hour, Min, Sec;

  if (sscanf(str, "%d:%d:%d", &Hour, &Min, &Sec) != 3) return false;
  tm.Hour = Hour;
  tm.Minute = Min;
  tm.Second = Sec;
  return true;
}

bool getDate(const char *str)
{
  char Month[12];
  int Day, Year;
  uint8_t monthIndex;

  if (sscanf(str, "%s %d %d", Month, &Day, &Year) != 3) return false;
  for (monthIndex = 0; monthIndex < 12; monthIndex++) {
    if (strcmp(Month, monthName[monthIndex]) == 0) break;
  }
  if (monthIndex >= 12) return false;
  tm.Day = Day;
  tm.Month = monthIndex + 1;
  tm.Year = CalendarYrToTm(Year);
  return true;
}

View raw code

This is what you will see in your Arduino IDE serial monitor:

Once the time and date is properly set, you can continue this project and upload the final sketch.

Code

The code provided turns off the LED every morning at 9:00 AM, and turns it on every evening at 7:00 PM. Copy the following code to the Arduino IDE and upload it to your Arduino board.

/*
 *
 * Complete project details at https://randomnerdtutorials.com    
 * Based on TimeAlarmExample from TimeAlarms library created by Michael Margolis
 *
 */

#include <TimeLib.h>
#include <TimeAlarms.h>
#include <Wire.h>
#include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t

const int led = 7; 

void setup() {
  // prepare pin as output
  pinMode(led, OUTPUT);
  digitalWrite(led, LOW);
  
  Serial.begin(9600);
  // wait for Arduino Serial Monitor
  while (!Serial) ; 
  
  // get and set the time from the RTC
  setSyncProvider(RTC.get);   
  if (timeStatus() != timeSet) 
     Serial.println("Unable to sync with the RTC");
  else
     Serial.println("RTC has set the system time");     
  
  // to test your project, you can set the time manually 
  //setTime(8,29,0,1,1,11); // set time to Saturday 8:29:00am Jan 1 2011

  // create the alarms, to trigger functions at specific times
  Alarm.alarmRepeat(9,0,0,MorningAlarm);  // 9:00am every day
  Alarm.alarmRepeat(19,0,0,EveningAlarm);  // 19:00 -> 7:00pm every day
}

void loop() {
  digitalClockDisplay();
  // wait one second between each clock display in serial monitor
  Alarm.delay(1000); 
}

// functions to be called when an alarm triggers
void MorningAlarm() {
  // write here the task to perform every morning
  Serial.println("Tturn light off");
  digitalWrite(led, LOW);
}
void EveningAlarm() {
  // write here the task to perform every evening
  Serial.println("Turn light on");
  digitalWrite(led, HIGH);
}

void digitalClockDisplay() {
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.println();
}
void printDigits(int digits) {
  Serial.print(":");
  if (digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

View raw code

This code is simple to understand and can be easily modified. Continue reading this page to learn how the code works.

Importing libraries

First, you import the needed libraries to create time alarms and to interact with the RTC module:

#include <TimeLib.h>
#include <TimeAlarms.h>
#include <Wire.h>
#include <DS1307RTC.h>

Getting the time

In the setup(), you get the time for the RTC with the following line:

Download our Free eBooks and Resources

setSyncProvider(RTC.get);

You also display a message on the serial monitor, so that you know whether the time has successfully synced:

if (timeStatus() != timeSet) 
  Serial.println("Unable to sync with the RTC");
else
 Serial.println("RTC has set the system time");

You can set the time manually – simply uncomment the next line. This is specially useful to test your sketches, because you can easily modify the time and test if the alarms are being triggered.

//setTime(8,29,0,1,1,11); // set time to Saturday 8:29:00am Jan 1 2011

Setting Alarms

The following line triggers the MorningAlarm function at 9:00 AM everyday. The MorningAlarm is defined after the loop().

Alarm.alarmRepeat(9,0,0, MorningAlarm); // 9:00am every day

To change the time, you just have to change the numbers 9,0,0, with your desired time. The first number is the hour, the second number is for the minutes, and the third for seconds.

The EveningAlarm function is triggered at 7:00 PM everyday.

 Alarm.alarmRepeat(19,0,0, EveningAlarm); // 19:00 -> 7:00pm every day

loop()

In the loop() you display the time on the serial monitor every second by calling the digitalClockDisplay() function, defined later in the code.

void loop() {
  digitalClockDisplay();
  Alarm.delay(1000); // wait one second between clock display
}

Defining the tasks

The MorningAlarm() and EveningAlarm() functions will be called at the time you’ve defined at the setup().

To edit your tasks, you just have to write your tasks inside the MorningAlarm() and EveningAlarm() functions.

void MorningAlarm() {
  // write here the task to perform every morning
  Serial.println("Alarm: - turn lights off");
  digitalWrite(led, LOW);
}
void EveningAlarm() {
  // write here the task to perform every evening
  Serial.println("Alarm: - turn lights on");
  digitalWrite(led, HIGH);
}

Here we’re just  printing a message on the serial monitor and turning an LED on and off.

The idea is that you use this example to make your Arduino perform a useful task everyday at the same time.

Wrapping up

In this tutorial we’ve shown you how you can perform daily tasks with the Arduino. The example provided is simple so that you can easily adapt it to your projects. Here’s some ideas of tasks you can automate using this technique:

  • Turn on/off lights at a specific time
  • Close your window blinds
  • Feed your pets

Do you intend to use the Arduino daily task in one of your projects? Let us know by posting a comment down below.

If you like Arduino, you may like the following blog posts:

We hope you’ve found this post useful. Thanks for reading.


Learn how to program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »

Learn how to program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »


Enjoyed this project? Stay updated by subscribing our weekly newsletter!

14 thoughts on “How To Do Daily Tasks with Arduino”

  1. Hello, Rui, as usual, a very good explanation for a basic circuit. However… 😉 Since quite a while I use DS3231 as RTC. This module is on one hand compatible with the 1307 but is way more accurate. After a week or so, DS1307 is some minutes ahead… DS3231 keeps time much better. And… It has also two built-in alarms. Definitely worth using as a clock!
    Greetings from Marc, and keep posting 🙂

    • Hi Marc.
      Thank you for sharing that.
      Many people have pointed that out – the DS3231 is way more accurate than the DS1307 RTC module and both work in a similar way.
      So, if people have both modules, the DS3231 is the best alternative.
      Regards,
      Sara

  2. The following code for setting an alarm for Saturday does not ‘explain’ how the day of Saturday is selected:
    //setTime(8,29,0,1,1,11); // set time to Saturday 8:29:00am Jan 1 2011

    What did I miss?

    • Hi v fisher.
      You don’t select the Saturday. You select the day.
      That day 1 Jan 2011 happens to be a Saturday.
      Regards.

    • Also note that you can set an alarm for a particular day of the week with this library (TimeAlarms)
      Here’s an example: github.com/PaulStoffregen/TimeAlarms/blob/master/examples/TimeAlarmExample/TimeAlarmExample.ino

      Take a look at line 31:
      Alarm.alarmRepeat(dowSaturday,8,30,30,WeeklyAlarm); // 8:30:30 every Saturday

      That runs the WeeklyAlarm() function every saturday (ignore the print that says Monday) (line 53).

      void WeeklyAlarm() {
      }

      Regards 🙂

    • Hi Andrew.
      This definitely can be used to turn on and off several devices at different times. You just have to create alarms for what you want to do.
      Regards.
      Sara 🙂

  3. Hi.Thank you for helping me. I am going to use this code to switch a light on in the morning, run for 2 hours and switch off. Then, the same light must switch on at Night and run for 3 hours, then switch off. This must happen daily. This is one of the first projects that really work as explained. thank you for that. Just need to add more code to the project.

  4. Ik wil een led laten branden van 9-17 uur. Hiervoor heb ik een programma gevonden.
    Deze werkt via een DS1307 clock. Ik wil nu een programma programmeren voor een DS 3231 clock maar weet niet hoe ik het programma juist moet programmeren.
    Kunnen jullie mij soms hulp verlenen?
    Alvast bedankt

    Hieronder het programma voor de DS1307 clock.

    /*
    *
    * Complete project details at https://randomnerdtutorials.com
    * Based on TimeAlarmExample from TimeAlarms library created by Michael Margolis
    *
    */

    #include
    #include
    #include
    #include // a basic DS1307 library that returns time as a time_t

    const int led = 7;

    void setup() {
    // prepare pin as output
    pinMode(led, OUTPUT);
    digitalWrite(led, LOW);

    Serial.begin(9600);
    // wait for Arduino Serial Monitor
    while (!Serial) ;

    // get and set the time from the RTC
    setSyncProvider(RTC.get);
    if (timeStatus() != timeSet)
    Serial.println(“Unable to sync with the RTC”);
    else
    Serial.println(“RTC has set the system time”);

    // to test your project, you can set the time manually
    //setTime(8,29,0,1,1,11); // set time to Saturday 8:29:00am Jan 1 2011

    // create the alarms, to trigger functions at specific times
    Alarm.alarmRepeat(9,0,0,MorningAlarm); // 9:00am every day
    Alarm.alarmRepeat(19,0,0,EveningAlarm); // 19:00 -> 7:00pm every day
    }

    void loop() {
    digitalClockDisplay();
    // wait one second between each clock display in serial monitor
    Alarm.delay(1000);
    }

    // functions to be called when an alarm triggers
    void MorningAlarm() {
    // write here the task to perform every morning
    Serial.println(“Tturn light off”);
    digitalWrite(led, LOW);
    }
    void EveningAlarm() {
    // write here the task to perform every evening
    Serial.println(“Turn light on”);
    digitalWrite(led, HIGH);
    }

    void digitalClockDisplay() {
    // digital clock display of the time
    Serial.print(hour());
    printDigits(minute());
    printDigits(second());
    Serial.println();
    }
    void printDigits(int digits) {
    Serial.print(“:”);
    if (digits < 10)
    Serial.print('0');
    Serial.print(digits);
    }

  5. Hallo, Beginner…
    Je kan het volledige programma van de DS 1307 gewoon stap per stap overnemen. De 3231 heeft dezelfde commando’s en dezelfde adressen als de 1307. Als het werkt met de 1307, werkt het ook met de 3231.De 3231 heeft als voordeel dat je ook alarmen kan programmeren.

    Groeten van Marc.;

Leave a Comment

Download our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.