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.

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:

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 build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Recommended Resources

Build a Home Automation System from Scratch » With Raspberry Pi, ESP8266, Arduino, and Node-RED.

Home Automation using ESP8266 eBook and video course » Build IoT and home automation projects.

Arduino Step-by-Step Projects » Build 25 Arduino projects with our course, even with no prior experience!

What to Read Next…


Enjoyed this project? Stay updated by subscribing our newsletter!

28 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 🙂

    Reply
    • 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

      Reply
  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?

    Reply
    • 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 🙂

      Reply
    • 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 🙂

      Reply
  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.

    Reply
  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);
    }

    Reply
  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.;

    Reply
        • Hi.
          What do you mean?
          If your sensor has a VCC pin and you want to turn it on and off, you can connect its VCC pin to an Arduino pin.
          Then, in your code, send a HIGH signal to that pin to turn it on digitalWrite(Pin, HIGH). If you want to remove power, send a LOW signal.
          Regards,
          Sara

          Reply
          • Thanks for the response, I tried that out but instead the sensor kept turning On and Off. I’m making use of a PIR sensor. Could the problem be from my arduino board.

  6. Hi
    I have followed your good explanation of “How To Do Daily Tasks with Arduino”, uploaded to the “Esp32 DOIT DevKit v1” board, and I use RTC “DS3231”. Arduino IDE compiler sketch without error. When I connect my board to Serial Monitor, the following appears:
    22: 09: 13.751 -> Rebooting … 22: 09: 13.751 -> ets Jun 8 2016 00:22:57 22: 09: 13.751 -> 22: 09: 13.751 -> rst: 0xc (SW_CPU_RESET), boot: 0x13 (SPI_FAST_FLASH_BOOT) 22: 09: 13.751 -> configsip: 0, SPIWP: 0xee 22: 09: 13.751 -> clk_drv: 0x00, q_drv: 0x00, d_drv: 0x00, cs0_drv: 0x00, hd_drv: 0x00, wp_drv: 0x00 22: 09: 13.751 -> mode: DIO, clock div: 1 22: 09: 13.751 -> load: 0x3fff0018, len: 4 22: 09: 13.751 -> load: 0x3fff001c, len: 928 22: 09: 13.751 -> ho 0 tail 12 room 4 22: 09: 13.751 -> load: 0x40078000, len: 8740 22: 09: 13.751 -> load: 0x40080400, len: 5788 22: 09: 13.751 -> entry 0x4008069c 22: 09: 13.843 -> Guru Meditation Error: Core 0 panic’ed (LoadProhibited). Exception was unhandled. 22: 09: 13.843 -> Core 0 register dump: 22: 09: 13.843 -> PC: 0x400d15d3 PS: 0x00060930 A0: 0x800d177e A1: 0x3ffe3b70 22: 09: 13.891 -> A2: 0x3ffc0310 A3: 0x00000000 A4: 0x00000000 A5: 0x00000000 22: 09: 13.891 -> A6: 0x00ff0000 A7: 0xff000000 A8: 0x800d15c7 A9: 0x3ffe3b40 22: 09: 13.891 -> A10: 0x3ffc0310 A11: 0x3ffbebe8 A12: 0x00000000 A13: 0x00000000 22: 09: 13.891 -> A14: 0x00000000 A15: 0x3ffbebe8 SAR: 0x00000020 EXCCAUSE: 0x0000001c 22: 09: 13.891 -> EXCVADDR: 0x0000001c LBEG: 0x4000c2e0 LEND: 0x4000c2f6 LCOUNT: 0xffffffff 22: 09: 13.891 -> 22: 09: 13,891 -> Backtrace: 0x400d15d3: 0x3ffe3b70 0x400d177b: 0x3ffe3b90 0x400d1786: 0x3ffe3bb0 0x400d5d13: 0x3ffe3bd0 0x40083261: 0x3ffe3bf0 0x4008343d: 0x3ffe3c20 0x40079017: 0x3ffe3c40 0x4007907d: 0x3ffe3c70 0x40079088: 0x3ffe3ca0 0x40079251: 0x3ffe3cc0 0x400806ce: 0x3ffe3df0 0x40007c31: 0x3ffe3eb0 0x4000073d: 0x3ffe3f20.
    It writes the same thing all the time at a very fast speed, and the LED does not turn on / off. Where is the error? Can you help me, so I can make it work.
    Sincerely Georg

    Reply
    • Hi.
      That error means that the code is crashing the ESP32 board.
      We built this example for the Arduino. So, it’s probably not compatible with the ESP32.
      Regards,
      Sara

      Reply
  7. can you look at this code. i took your temperature alarm code and applied it with this code so i can have it send a email at 7:00am every day but it gives me a error of ‘alarm’ does not name a type. thank you for your help.
    #include <WiFi.h>
    #include <AsyncTCP.h>
    #include <ESPAsyncWebServer.h>
    #include <OneWire.h>
    #include <DallasTemperature.h>
    #include “ESP32_MailClient.h”
    #include <TimeLib.h>
    #include <TimeAlarms.h>

    const char* ssid = “123456”;
    const char* password = “123456”;

    #define emailSenderAccount “[email protected]
    #define emailSenderPassword “1234”
    #define smtpServer “smtp.gmail.com”
    #define smtpServerPort 465
    #define emailSubject “[ALERT] CES Building Loop Temperature”

    String inputMessage = “[email protected]”;
    String enableEmailChecked = “checked”;
    String inputMessage2 = “true”;
    // Default Temperature Thresholds
    String inputMessage3 = “95”;
    String inputMessage4 = “65”;
    String lastTemperature;

    const char index_html[] PROGMEM = R”rawliteral(

    Email Notification with Temperature

    DS18B20 Temperature

    %TEMPERATURE% °F

    ESP Email Notification

    Email Address
    Enable Email Notification
    Upper Temperature Threshold
    Lower Temperature Threshold

    )rawliteral”;

    void notFound(AsyncWebServerRequest *request) {
    request->send(404, “text/plain”, “Not found”);
    }

    AsyncWebServer server(80);

    String processor(const String& var){
    //Serial.println(var);
    if(var == “TEMPERATURE”){
    return lastTemperature;
    }
    else if(var == “EMAIL_INPUT”){
    return inputMessage;
    }
    else if(var == “ENABLE_EMAIL”){
    return enableEmailChecked;
    }
    else if(var == “UPPER_THRESHOLD”){
    return inputMessage3;
    }
    else if(var == “LOWER_THRESHOLD”){
    return inputMessage4;
    }
    return String();
    }

    bool emailSent = false;

    const char* PARAM_INPUT_1 = “email_input”;
    const char* PARAM_INPUT_2 = “enable_email_input”;
    const char* PARAM_INPUT_3 = “upper_threshold_input”;
    const char* PARAM_INPUT_4 = “lower_threshold_input”;

    unsigned long previousMillis = 0;
    const long interval = 5000;

    const int oneWireBus = 4;
    OneWire oneWire(oneWireBus);
    DallasTemperature sensors(&oneWire);

    SMTPData smtpData;

    void setup() {

    Serial.begin(115200);
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);
    if (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println(“WiFi Failed!”);
    return;
    }
    Serial.println();
    Serial.print(“ESP IP Address: http://“);
    Serial.println(WiFi.localIP());

    sensors.begin();

    server.on(“/”, HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, “text/html”, index_html, processor);
    });

    server.on(“/get”, HTTP_GET, [] (AsyncWebServerRequest *request) {

    if (request->hasParam(PARAM_INPUT_1)) {
    inputMessage = request->getParam(PARAM_INPUT_1)->value();

    if (request->hasParam(PARAM_INPUT_2)) {
    inputMessage2 = request->getParam(PARAM_INPUT_2)->value();
    enableEmailChecked = "checked";
    }
    else {
    inputMessage2 = "false";
    enableEmailChecked = "";
    }

    if (request->hasParam(PARAM_INPUT_3)) {
    inputMessage3 = request->getParam(PARAM_INPUT_3)->value();
    }
    if (request->hasParam(PARAM_INPUT_4)) {
    inputMessage4 = request->getParam(PARAM_INPUT_4)->value();
    }
    }
    else {
    inputMessage = "No message sent";
    }
    Serial.println(inputMessage);
    Serial.println(inputMessage2);
    Serial.println(inputMessage3);
    Serial.println(inputMessage4);
    request->send(200, "text/html", "HTTP GET request sent to your ESP.<br><a href=\"/\">Return to Home Page</a>");

    });
    server.onNotFound(notFound);
    server.begin();
    }
    Alarm.alarmRepeat(7,0,0, MorningAlarm); // 7:00am every day
    void loop() {

    unsigned long currentMillis = millis();
    if (currentMillis – previousMillis >= interval) {
    previousMillis = currentMillis;
    sensors.requestTemperatures();
    // Temperature in Fahrenheit degrees
    float temperature = sensors.getTempFByIndex(0);
    Serial.print(temperature);
    Serial.println(” *F”);

    // Temperature in Fahrenheit degrees
    /*float temperature = sensors.getTempFByIndex(0);
    SerialMon.print(temperature);
    SerialMon.println(" *F");*/

    lastTemperature = String(temperature);

    // Check if temperature is above threshold and if it needs to send the Email alert
    if(temperature > inputMessage3.toFloat() && inputMessage2 == "true" && !emailSent){
    String emailMessage = String("Temperature above threshold. Current temperature: ") +
    String(temperature) + String("F");
    if(sendEmailNotification(emailMessage)) {
    Serial.println(emailMessage);
    emailSent = true;
    }

    void MorningAlarm () {
    Serial.println(temerature);
    }
    else {
    Serial.println(“Email failed to send”);
    }
    }
    // Check if temperature is below threshold and if it needs to send the Email alert
    if(temperature < inputMessage4.toFloat() && inputMessage2 == “true” && !emailSent){
    String emailMessage = String(“Temperature below threshold. Current temperature: “) +
    String(temperature) + String(“F”);
    if(sendEmailNotification(emailMessage)) {
    Serial.println(emailMessage);
    emailSent = true;
    }
    else {
    Serial.println(“Email failed to send”);
    }
    }
    }
    }

    bool sendEmailNotification(String emailMessage){
    // Set the SMTP Server Email host, port, account and password
    smtpData.setLogin(smtpServer, smtpServerPort, emailSenderAccount, emailSenderPassword);

    // For library version 1.2.0 and later which STARTTLS protocol was supported,the STARTTLS will be
    // enabled automatically when port 587 was used, or enable it manually using setSTARTTLS function.
    //smtpData.setSTARTTLS(true);

    // Set the sender name and Email
    smtpData.setSender(“CES Loop Sensor”, emailSenderAccount);

    // Set Email priority or importance High, Normal, Low or 1 to 5 (1 is highest)
    smtpData.setPriority(“High”);

    // Set the subject
    smtpData.setSubject(emailSubject);

    // Set the message with HTML format
    smtpData.setMessage(emailMessage, true);

    // Add recipients
    smtpData.addRecipient(inputMessage);

    smtpData.setSendCallback(sendCallback);

    // Start sending Email, can be set callback function to track the status
    if (!MailClient.sendMail(smtpData)) {
    Serial.println(“Error sending Email, ” + MailClient.smtpErrorReason());
    return false;
    }
    // Clear all data from Email object to free memory
    smtpData.empty();
    return true;
    }

    // Callback function to get the Email sending status
    void sendCallback(SendStatus msg) {
    // Print the current status
    Serial.println(msg.info());

    // Do something when complete
    if (msg.success()) {
    Serial.println(“—————-“);
    }
    }

    Reply
  8. Hi
    I´m a beginner and trying to figure it out. It took me weeks before i discovered that my DS3231 device was damaged which was very frustrating because i thought i was doing something wrong.
    Now i have it finally running and i´m using your sketch to switch a LEd on and off just like it´s explained here.
    But what happens is that when i upload the sketch the LED goes on…when it reaches the Time for “MorningAlarm it goes off…when it reaches the time for the “EveningAlarm” it goes on again !!!!
    What am i doing wrong !!! Can somebody help me please…this is so frustrating.

    Reply
  9. Hello
    I have obtained the date and time by connecting to Wi-Fi and I want to write one or more alarms in the program, can anyone help me?
    my Program:
    /*
    Rui Santos
    Complete project details at https://RandomNerdTutorials.com/esp32-date-time-ntp-client-server-arduino/

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files.

    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.
    */

    #include <WiFi.h>
    #include “time.h”

    const char* ssid = “1234”;
    const char* password = “1234”;

    const char* ntpServer = “pool.ntp.org”;
    const long gmtOffset_sec = 12600;
    const int daylightOffset_sec = 3600;

    void setup(){
    Serial.begin(115200);
    // Connect to Wi-Fi
    Serial.print(“Connecting to “);
    Serial.println(ssid);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(“.”);
    }
    Serial.println(“”);
    Serial.println(“WiFi connected.”);

    // Init and get the time
    configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
    printLocalTime();

    //disconnect WiFi as it’s no longer needed
    WiFi.disconnect(true);
    WiFi.mode(WIFI_OFF);
    }

    void loop(){

    printLocalTime();

    delay(1000);

    }

    void printLocalTime(){
    struct tm timeinfo;
    if(!getLocalTime(&timeinfo)){
    Serial.println(“Failed to obtain time”);
    return;
    }
    Serial.println(&timeinfo, “%A, %B %d %Y %H:%M:%S”);

    }

    Reply
  10. Hello to everyone, I would like to resettable time schedule via Nextion HMI screen.

    I am using Arduino mega and would like to make a kind of greenhouse. That’s why I need the resettable time scheduled watering system. When I put Alarm.alarmRepeat into void setup() function it works but I can not set it again without rebooting.

    When I put Alarm.alarmRepeat into void loop() function only the first alarm is triggered. The second alarm doesn’t trigger.

    Are there any suggestions for me?

    Reply
    • “onceOnly Alarms and Timers are freed when they are triggered so another onceOnly alarm can be set to trigger again.
      There is no limit to the number of times a onceOnly alarm can be reset.

      The following fragment gives one example of how a timerOnce task can be rescheduled:
      Alarm.timerOnce(random(10), randomTimer); // trigger after random number of seconds

      void randomTimer(){
      int period = random(2,10); // get a new random period
      Alarm.timerOnce(period, randomTimer); // trigger for another random period”
      …From the docs.

      He is using a random variable, but you could also use one you have chosen in place of “period”. I didn’t try it, but I suspect this would need to reside in loop() or a function run from loop(), otherwise the alarm would not see the variable change.

      Late, but maybe it will help?
      Dave

      Reply
  11. Is there a possibility to have an “on-auto-off” switch which has priority over the timer?
    Say I want to turn the lights “on” manually already one hour earlier. Before I leave, I turn to “auto” that in the next morning they turn on again.
    Or I come earlier in the morning and switch manually “off”. When I leave I switch to “auto” to get back to the original rhythm.

    Reply
  12. I tried running the code, but I get an error -“tm eLements_t-tm does not name a type. Did you mean TimeLib_month_t?

    What should I do?

    Reply
  13. Hi, I would love to get this sketch working to open and close my shades every morning. This would be perfect….I included the libraries below… (Wire) because I read there is some dependency with one of the other libraries??
    #include <Wire.h>
    #include <TimeLib.h>
    #include <DS1307RTC.h>
    – I tried installing TimeLib, but Arduino installs TIme.
    I’m using a DS3231, but still trying to use DS1307RTC library. When I changed it to DS3231RTC library I had errors. But now I am getting an error on the following line in the sketch– ‘tmElements_t’
    the error is—“does not name a type; did you mean ‘timelib_month_t’?”
    What do I do?

    tmElements_t tm;

    Reply

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.