Alarm Function

MRK1010 board

Trying to accomplish a task once a day, at a certain time. That task is send an email via Blynk with a daily max sensor value calculation (that code is omitted). Through my searching I have found an alarm function that seems to be the hot ticket, although, of course I can't get it to work. I think it doesn't work because it does not know the time? I am getting my current time from NTP server, but I think I need code that is something along of the lines of telling setTime, what time is coming in from server. Anybody mind telling me what I am doing wrong?

#include <Smoothed.h>
#include <Blynk.h>
#include <SPI.h>
#include <WiFiNINA.h>
#include <BlynkSimpleWiFiNINA.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <TimeAlarms.h>

char ssid[] = "-----";       
char pass[] = "-----";         
int status = WL_IDLE_STATUS;           

const char auth[] = "dcy3wWSGO-ApB1uKvh9cUiEZ21HrPiab";
BlynkTimer timer;
WidgetLCD lcd(V1);
WidgetLED ledChange(V3);

// Define NTP Client to get time
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);

// Variables to save date and time
String formattedDate;
String dayStamp;
String timeStamp;

const byte wifiPin = 4;            
const byte noWifiPin = 5;  

void setup() {
  
  Serial.begin(9600);
  
  int attempts = 0;
  while (status != WL_CONNECTED && attempts < 6) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.print(ssid);  
    status = WiFi.begin(ssid, pass);
    delay(10000);
    attempts++;
  }

  if (status != WL_CONNECTED) {
    Serial.print("Failed to connect to Wifi!");
    digitalWrite(noWifiPin, HIGH);   
    delay(1000);                       
    digitalWrite(noWifiPin, LOW);    
    delay(1000);    
    while (true);
  }

  Serial.print("You're connected to the network");
  digitalWrite(wifiPin, HIGH);

  Blynk.begin(auth, ssid, pass);
  timer.setInterval(1000L, myTimerEvent);

  pinMode(wifiPin, OUTPUT);
  pinMode(noWifiPin, OUTPUT);
  
  // Initialize a NTPClient to get time
  timeClient.begin();
  timeClient.setTimeOffset(-21600);
  
  Alarm.alarmRepeat(21,32,0, EmailAlarm); 
}

void loop() {
  
  Blynk.run();
  timer.run();
  
  timeClient.update();
}

void myTimerEvent()
{
  
  lcd.print(4, 0, "Current Time"); 
  lcd.print(4, 1, timeClient.getFormattedTime()); 
}

void EmailAlarm(){
 Blynk.email("-----", "FilterLynk Condition", "Test";
 
}

Please? Am I posting in the wrong place? I have been searching through the NTP examples and libraries, trying to understand what I need to do. I have found NTP client library for MKR boards, but it won't compile due to "redefinition of "class WiFiClient". So that has got me banging my head again the desk. That code is here-

/*
Copyright 2016 German Martin (gmag11@gmail.com). All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met :

1. Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list
of conditions and the following disclaimer in the documentation and / or other materials
provided with the distribution.

THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ''AS IS'' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.IN NO EVENT SHALL <COPYRIGHT HOLDER> OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation are those of the
authors and should not be interpreted as representing official policies, either expressed
or implied, of German Martin
*/

/*
 Name:		NtpClientAvr.ino
 Created:	20/08/2016
 Author:	gmag11@gmail.com
 Editor:	http://www.visualmicro.com
*/

#include <WiFiClient.h>
#include <SPI.h>
#include <WiFiUdp.h>
#include <WiFi101.h>
#include <TimeLib.h>
#include <NtpClientLib.h>
#include <Dns.h>
#include <Dhcp.h>
#include "WifiConfig.h"

#ifndef WIFI_CONFIG_H
#define YOUR_WIFI_SSID "YOUR_WIFI_SSID"
#define YOUR_WIFI_PASSWD "YOUR_WIFI_PASSWD"
#endif // !WIFI_CONFIG_H

#define SHOW_TIME_PERIOD 5000


void setup () {
    Serial.begin (115200);
    WiFi.begin (YOUR_WIFI_SSID, YOUR_WIFI_PASSWD);
    while (WiFi.status () != WL_CONNECTED) {
        Serial.print ('.');
        delay (500);
    }
    Serial.println ();
    NTP.onNTPSyncEvent ([](NTPSyncEvent_t error) {
        if (error) {
            Serial.print ("Time Sync error: ");
            if (error == noResponse)
                Serial.println ("NTP server not reachable");
            else if (error == invalidAddress)
                Serial.println ("Invalid NTP server address");
        } else {
            Serial.print ("Got NTP time: ");
            Serial.println (NTP.getTimeDateString (NTP.getLastNTPSync ()));
        }
    });
    NTP.setInterval (63);
    NTP.setNTPTimeout (1000);
    NTP.begin ("pool.ntp.org", 1, true);
}

void loop () {
    static int i = 0;
    static int last = 0;

    if ((millis () - last) > SHOW_TIME_PERIOD) {
        //Serial.println(millis() - last);
        last = millis ();
        Serial.print (i); Serial.print (" ");
        Serial.print (NTP.getTimeDateString ()); Serial.print (" ");
        Serial.print (NTP.isSummerTime () ? "Summer Time. " : "Winter Time. ");
        Serial.print ("WiFi is ");

        Serial.print ((WiFi.status () == WL_CONNECTED) ? "connected" : "not connected"); Serial.print (". ");
        Serial.print ("Uptime: ");
        Serial.print (NTP.getUptimeString ()); Serial.print (" since ");
        Serial.println (NTP.getTimeDateString (NTP.getFirstSync ()).c_str ());

        i++;
    }
    delay (0);
}

Again, all I am looking to do is input time into my code. So I need to connect to NTP server, then at a certain time once a day, perform an action. I am lost as lost can be.

Is there a blynk rtc widget you can use?

I'm not familiar with blynk, and if you were just using the MKR1010 and wifi it would be straightforward to synch the time library with an NTP client request.

Also you might get some help here: https://esp32.com

Why not work on a new sketch that just gets the time from the server and then periodically prints that time out to the monitor. Then move on to integrating that code into your main sketch?

Thanks Idahowalker, that write-up is really easy to follow. Using the link from Idahowalker, I got this sketch

#include <WiFi.h>
#include "time.h"


const char* ssid       = "-----";
const char* password   = "----";

const char* ntpServer = "pool.ntp.org";
const long  gmtOffset_sec = -25200;
const int   daylightOffset_sec = 3600;

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

void setup()
{
  Serial.begin(115200);
  
  //connect to WiFi
  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
  }
  Serial.println(" CONNECTED");
  
  //init and get the time
  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
  printLocalTime();

}

void loop()
{
  delay(1000);
  printLocalTime();
}

But it won't compile, it says "getlocaltime" was not declared in this scope? I am using Arduino online IDE.

getlocaltime" was not declared in this scope

It wasn't.
What's your point?

TheMemberFormerlyKnownAsAWOL:
It wasn't.
What's your point?

I apologize, I should have been more clear. Can someone tell me what needs to happen to get this error to clear, so the code will compile?

You've told us that the error message says "getlocaltime" was not declared, but the code you posted does not include the string "getlocaltime", so it is hard to see why the compiler should complain in that way.

getLocalTime inside the Void printLocalTime

I just tried this sketch on my ESP32 and it works fine with the correct ssid and password:

#include <WiFi.h>
#include "time.h"

const char* ssid       = "SendMeInAPMyourSSDOB";
const char* password   = "JustKidding";

const char* ntpServer = "pool.ntp.org";
const long  gmtOffset_sec = 3600;
const int   daylightOffset_sec = 3600;

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

void setup()
{
  Serial.begin(115200);
  
  //connect to WiFi
  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
  }
  Serial.println(" 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()
{
  delay(1000);
  printLocalTime();
}

Can you copy the above sketch into a new project, fix the password and ssid, upload and let us know how it went?

Taking this back to your first post.

I am getting my current time from NTP server, but I think I need code that is something along of the lines of telling setTime, what time is coming in from server

Does the Arduino TimeLib.h run on the MKR1010?

If so, then you should be able to use the setTime() command with the NTPClient.h function

.getEpochTime() instead of the .getFormattedTime()

Idahowalker:
I just tried this sketch on my ESP32 and it works fine with the correct ssid and password:

#include <WiFi.h>

#include "time.h"

const char* ssid      = "SendMeInAPMyourSSDOB";
const char* password  = "JustKidding";

const char* ntpServer = "pool.ntp.org";
const long  gmtOffset_sec = 3600;
const int  daylightOffset_sec = 3600;

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

void setup()
{
  Serial.begin(115200);
 
  //connect to WiFi
  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
  }
  Serial.println(" 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()
{
  delay(1000);
  printLocalTime();
}



Can you copy the above sketch into a new project, fix the password and ssid, upload and let us know how it went?

Same message; "getLocalTime" not declared in this scope.

When you select board type did you select the SAM or the ESP32?

cattledog:
Taking this back to your first post.

Does the Arduino TimeLib.h run on the MKR1010?

If so, then you should be able to use the setTime() command with the NTPClient.h function

.getEpochTime() instead of the .getFormattedTime()

I believe that TimeLib.h does run on the MKR1010, as I think I have used it before on other sketches and it ran fine. I am trying to find some sample code using this .getEposchTime().

I have attached a photo, hope it answers your question Idahowalker.

photo

RealHousewifeofIdaho:
photo

You do not have an ESP32 you have a Arduino SAMD board. That's why ESP32 stuff does not work on your board.

Well that is real bummer. I have been spinning my wheels for no reason then. I did find a sketch under NTPClient library that says it is for MKR boards--

/*
Copyright 2016 German Martin (gmag11@gmail.com). All rights reserved.
*/

/*
 Name: NtpClientAvr.ino
 Created: 20/08/2016
 Author: gmag11@gmail.com
 Editor: http://www.visualmicro.com
*/

#include <WiFiClient.h>
#include <SPI.h>
#include <WiFiUdp.h>
#include <WiFi101.h>
#include <TimeLib.h>
#include <NtpClientLib.h>
#include <Dns.h>
#include <Dhcp.h>
#include "WifiConfig.h"

#ifndef WIFI_CONFIG_H
#define YOUR_WIFI_SSID "YOUR_WIFI_SSID"
#define YOUR_WIFI_PASSWD "YOUR_WIFI_PASSWD"
#endif // !WIFI_CONFIG_H

#define SHOW_TIME_PERIOD 5000


void setup () {
    Serial.begin (115200);
    WiFi.begin (YOUR_WIFI_SSID, YOUR_WIFI_PASSWD);
    while (WiFi.status () != WL_CONNECTED) {
        Serial.print ('.');
        delay (500);
    }
    Serial.println ();
    NTP.onNTPSyncEvent ([](NTPSyncEvent_t error) {
        if (error) {
            Serial.print ("Time Sync error: ");
            if (error == noResponse)
                Serial.println ("NTP server not reachable");
            else if (error == invalidAddress)
                Serial.println ("Invalid NTP server address");
        } else {
            Serial.print ("Got NTP time: ");
            Serial.println (NTP.getTimeDateString (NTP.getLastNTPSync ()));
        }
    });
    NTP.setInterval (63);
    NTP.setNTPTimeout (1000);
    NTP.begin ("pool.ntp.org", 1, true);
}

void loop () {
    static int i = 0;
    static int last = 0;

    if ((millis () - last) > SHOW_TIME_PERIOD) {
        //Serial.println(millis() - last);
        last = millis ();
        Serial.print (i); Serial.print (" ");
        Serial.print (NTP.getTimeDateString ()); Serial.print (" ");
        Serial.print (NTP.isSummerTime () ? "Summer Time. " : "Winter Time. ");
        Serial.print ("WiFi is ");

        Serial.print ((WiFi.status () == WL_CONNECTED) ? "connected" : "not connected"); Serial.print (". ");
        Serial.print ("Uptime: ");
        Serial.print (NTP.getUptimeString ()); Serial.print (" since ");
        Serial.println (NTP.getTimeDateString (NTP.getFirstSync ()).c_str ());

        i++;
    }
    delay (0);
}

Put when I compile it just says "redefinition of "class WiFiClient". Any idea what that means?

I would also like to add that, for whatever reason, even though I don't have a ESP32, the code below works and prints out the time.

#include <Smoothed.h>
#include <Blynk.h>
#include <SPI.h>
#include <WiFiNINA.h>
#include <BlynkSimpleWiFiNINA.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <TimeLib.h>
#include <TimeAlarms.h>

char ssid[] = "-----";       
char pass[] = "-----";         
int status = WL_IDLE_STATUS; 
const byte wifiLedPin = 4;
const byte noWifiLedPin = 5;

const char auth[] = "dcy3wWSGO-ApB1uKvh9cUiEZ21HrPiab";
BlynkTimer timer;
WidgetLCD lcd(V1);
WidgetLED ledChange(V3);

// Define NTP Client to get time
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);

// Variables to save date and time
String formattedDate;
String dayStamp;
String timeStamp;
  

void setup() {
  
  Serial.begin(9600);
  
  int attempts = 0;
  while (status != WL_CONNECTED && attempts < 6) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.print(ssid);  
    status = WiFi.begin(ssid, pass);
    delay(10000);
    attempts++;
  }

  if (status != WL_CONNECTED) {
    Serial.print("Failed to connect to Wifi!");
    digitalWrite(noWifiLedPin, HIGH);   
    delay(1000);                       
    digitalWrite(noWifiLedPin, LOW);    
    delay(1000);    
    while (true);
  }

  Serial.print("You're connected to the network");
  digitalWrite(wifiLedPin, HIGH);

  Blynk.begin(auth, ssid, pass);
  timer.setInterval(1000L, myTimerEvent);

  pinMode(wifiLedPin, OUTPUT);
  pinMode(noWifiLedPin, OUTPUT);
  
  // Initialize a NTPClient to get time
  timeClient.begin();
  timeClient.setTimeOffset(-21600);
  
  
  Alarm.alarmRepeat(21,32,0, EmailAlarm); 
}

void loop() {
  
  Blynk.run();
  timer.run();
  
  timeClient.update();
}

void myTimerEvent()
{
  
  lcd.print(4, 0, "Curent Time"); // use: (position X: 0-15, position Y: 0-1, "Message you want to print")
  lcd.print(4, 1, timeClient.getFormattedTime()); 
}

void EmailAlarm(){
 Blynk.email("mrcparker90@gmail.com", "FilterLynk Condition", "Test");
 
}

If I could just get the alarm function to work with this code, I would be all set to move forward on this project.

See if this doesn't synchronize the Time Library to the NTP time. I don't have your environment, so it is untested.

#include <Smoothed.h>
#include <Blynk.h>
#include <SPI.h>
#include <WiFiNINA.h>
#include <BlynkSimpleWiFiNINA.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <TimeLib.h>
#include <TimeAlarms.h>

char ssid[] = "-----";
char pass[] = "-----";
int status = WL_IDLE_STATUS;
const byte wifiLedPin = 4;
const byte noWifiLedPin = 5;

const char auth[] = "dcy3wWSGO-ApB1uKvh9cUiEZ21HrPiab";
BlynkTimer timer;
WidgetLCD lcd(V1);
WidgetLED ledChange(V3);

// Define NTP Client to get time
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);

// Variables to save date and time
String formattedDate;
String dayStamp;
String timeStamp;


void setup() {

  Serial.begin(9600);

  int attempts = 0;
  while (status != WL_CONNECTED && attempts < 6) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.print(ssid);
    status = WiFi.begin(ssid, pass);
    delay(10000);
    attempts++;
  }

  if (status != WL_CONNECTED) {
    Serial.print("Failed to connect to Wifi!");
    digitalWrite(noWifiLedPin, HIGH);
    delay(1000);
    digitalWrite(noWifiLedPin, LOW);
    delay(1000);
    while (true);
  }

  Serial.print("You're connected to the network");
  digitalWrite(wifiLedPin, HIGH);

  Blynk.begin(auth, ssid, pass);
  timer.setInterval(1000L, myTimerEvent);

  pinMode(wifiLedPin, OUTPUT);
  pinMode(noWifiLedPin, OUTPUT);

  // Initialize a NTPClient to get time
  timeClient.begin();
  timeClient.setTimeOffset(-21600);

  setSyncProvider(getNtpTime);  //corrected for capitalization 

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

 Alarm.alarmRepeat(21, 32, 0, EmailAlarm);
}

void loop() {

  Blynk.run();
  timer.run();
  timeClient.update();
}

void myTimerEvent()
{
   timeDateDisplay();
  //lcd.print(4, 0, "Curent Time"); // use: (position X: 0-15, position Y: 0-1, "Message you want to print")
  //lcd.print(4, 1, timeClient.getFormattedTime());
}

void EmailAlarm() {
  Blynk.email("mrcparker90@gmail.com", "FilterLynk Condition", "Test");

}

time_t getNtpTime()
{
  time_t epochStamp = timeClient.getEpochTime(); //corrected to add semicolon
  return epochStamp;
}

void timeDateDisplay(void)
{
 
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print(' ');
  Serial.print(month());
  Serial.print("/");
  Serial.print(day());
  Serial.print("/");
  Serial.print(year()); 
  Serial.println(); 
 // Serial.print("Unix Time "); //something may not be correct here?
 // Serial.println(now());
 //Serial.println();
}

void printDigits(int digits)
{
  // utility function for digital clock display: prints preceding colon and leading 0
  Serial.print(':');
  if(digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

It doesn't like it. Line 68, "getNTPTime" not declared in this scope. Any ideas what that means?

And thank you and everyone else who has tried to help so far.