ARDUINO

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!

header-200.png?w=828&quality=100&strip=all&ssl=1

Schematic

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

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

DS1307 RTC Module PinWiring to Arduino Uno
SCLA5
SDAA4
VCC5V
GNDGND

Installing libraries

For this example you need to install the following libraries: TimeTimeAlarms, 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:

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.


Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now