Alarms using TimeAlarms.h not working in my own code

Hi Everyone,

I’ve been trying to get the some times alarms working using the library TimeAlarms.h. To start, i uploaded the example program i found here: TimeAlarms.html This works like a charm.

Since i’m using an NTP server to sync the initial time, I changed that example somewhat to accomodate that. this still seemed to work.

Now i tried implementing this into my own project. But when I do, the alarms never seem to trigger.

I’ve tried a few things like Adding a while(timeStatus()== timeNotSet); to make sure the time is set, adding a one-time trigger in the loop to set the alarms there instead of during inside the setup, adding the Timealarms in the UDP loop after it acquired the time.

I hope someone can point me into the right direction.

Here’s the code i have (Without some code that handles the webpage)

#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
#include <SdFat.h>
#include "DHT.h"
#include <Time.h>
#include <TimeAlarms.h>

/////////////////////////
//// SD CARD settings
/////////////////////////
SdFat sd;                         // SD instance voor lib
Sd2Card card;
SdFile myFile;                    // file variabele voor sd-library
char buffer;                      // SD read buffer
char page;                        // nummer van aangeroepen pagina
const uint8_t SdChipSelect = 4;
////////////////////////
//// Temp/Hum Sensor settings
///////////////////////
#define DHTPIN 8     // what pin we're connected to
#define DHTTYPE DHT22   // DHT 22  (AM2302)
DHT dht(DHTPIN, DHTTYPE);
float h = 0;
float t = 0;
float f  = 0;
float TempLow = 50;
float TempHigh = -50;
float HumLow = 100;
float HumHigh = -100;
////////////////////////
//// Netwerk kaart settings
///////////////////////
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0E, 0xF5, 0x3E };
IPAddress ip(192,168,1,3);
IPAddress gateway(192,168,1,1); 
IPAddress subnet(255,255,255,0);
EthernetServer server(80);
EthernetClient client;
//////////////////////
//// UDP/Time Settings
//////////////////////
unsigned int localPort = 8888;  
IPAddress timeServer(129, 250, 35, 250); //pool.ntp.org
const int NTP_PACKET_SIZE= 48; // NTP time stamp is in the first 48 bytes of the message
byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets 
EthernetUDP Udp; // A UDP instance to let us send and receive packets over UDP
const  int timeZoneOffset = +1; // GMT zone;


int freeRam () {
  extern int __heap_start, *__brkval; 
  int v; 
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval); 
}


void setup() {
  Serial.begin(9600);
  pinMode(10, OUTPUT); 
  digitalWrite(10, HIGH);  
  delay(1000);
  if (!sd.begin(SdChipSelect, SPI_HALF_SPEED)) {
    Serial.println(F("SD initialization failed!"));
    return;
  }
    Serial.println(F("SD initialization done."));
  Ethernet.begin(mac, ip, gateway, gateway, subnet);        // start ethernet shield
  server.begin();                 // start server
  Serial.print(F("server is Online op: "));
  Serial.println(Ethernet.localIP());  
  delay(1000);
  Udp.begin(localPort);
  delay(1000);
  setSyncProvider(getNtpTime);
  while(timeStatus()== timeNotSet);
  Serial.print(F("Starten van Temperatuur sensor: "));
  dht.begin();
  delay(2000);
  
  TempReader(); // gather temperature once before moving on.
  // lets set the alarms.
  Alarm.timerRepeat(900, SQLLogger);
  Alarm.timerRepeat(15, Repeats);            // timer for every 15 seconds    
  Alarm.timerRepeat(20, TempReader);
 
}
void loop() {
  //Serial.println(freeRam());
  delay(1000); //added delay to not spam the console
  digitalClockDisplay();
  
  client = server.available();
  boolean currentLineIsFirst = true; 
  if (client) {
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        if (c == '\n' && currentLineIsBlank) {
          if (page == '1') {
           // removed all webpage stuff for readability
          }   // end page 
          else {
            client.println(F("HTTP/1.1 403 FORBIDDEN"));
            client.println(F("Content-Type: text/html"));
            client.println();
            client.print(F("<h1>403 FORBIDDEN</h1>"));
          }
          page = 0;      // reset page variabele
          break;
        }//end if currentlineisBlank
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
          currentLineIsFirst = false;
        } 
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
        if (currentLineIsFirst && c == '?') {
          // found ? so read pagenumber
          page = client.read();
        }
      }//end if client available
    }//end while client connected
    delay(1);
    // close the connection:
    client.stop();
  }//end if client
  
}//end void loop

/*-------- code for file manipulation  ----------*/
void Read_File_Upto_FS() {
  while ((buffer = myFile.read()) != 28) {
    client.print((char)buffer);    
  }  
}

void Read_File_Upto_End() {
  while ((buffer = myFile.read()) >= 0) {
    client.print((char)buffer);    
  }  
}

void Skip_File_Upto_FS() {
  while ((buffer = myFile.read()) != 28) {
    // nothing
  }  
}

/*-------- code used for alarm testing  ----------*/
void Repeats(){
  Serial.println("15 second timer");         
}

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

void digitalClockDisplay()
{
  // digital clock display of the time
  Serial.print(hour());
  Serial.print(minute());
  Serial.print(second());
  Serial.println(); 
}
/*-------- NTP code ----------*/

unsigned long getNtpTime()
{
 sendNTPpacket(timeServer); // send an NTP packet to a time server
 delay(1000);
 if ( Udp.parsePacket() ) {  
   // We've received a packet, read the data from it
   Udp.read(packetBuffer,NTP_PACKET_SIZE);  // read the packet into the buffer

   //the timestamp starts at byte 40 of the received packet and is four bytes,
   // or two words, long. First, esxtract the two words:

   unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
   unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);  
   // combine the four bytes (two words) into a long integer
   // this is NTP time (seconds since Jan 1 1900):
   unsigned long secsSince1900 = highWord << 16 | lowWord; 
   const unsigned long seventyYears = 2208988800UL;     
   // subtract seventy years and add the time zone:
   unsigned long epoch = secsSince1900 - seventyYears + (timeZoneOffset * 3600L);
   return epoch;
 }

 return 0;
}

// send an NTP request to the time server at the given address 
unsigned long sendNTPpacket(IPAddress& address)
{
 // set all bytes in the buffer to 0
 memset(packetBuffer, 0, NTP_PACKET_SIZE); 
 // Initialize values needed to form NTP request
 // (see URL above for details on the packets)
 packetBuffer[0] = 0b11100011;   // LI, Version, Mode
 packetBuffer[1] = 0;     // Stratum, or type of clock
 packetBuffer[2] = 6;     // Polling Interval
 packetBuffer[3] = 0xEC;  // Peer Clock Precision
 // 8 bytes of zero for Root Delay & Root Dispersion
 packetBuffer[12]  = 49; 
 packetBuffer[13]  = 0x4E;
 packetBuffer[14]  = 49;
 packetBuffer[15]  = 52;

 // all NTP fields have been given values, now
 // you can send a packet requesting a timestamp:   
 Udp.beginPacket(address, 123); //NTP requests are to port 123
 Udp.write(packetBuffer,NTP_PACKET_SIZE);
 Udp.endPacket(); 
}
void WeekDay_Morning(){
  Serial.println(F("Weekday morning alarm triggered"));
}
void SQLLogger(){
  Serial.println(freeRam());
  Serial.println(F("SQL Logger alarm triggered!"));
}
void TempReader(){
    Serial.println(freeRam());
    Serial.println("Time to gather the Temperature and Humidity!");
    h = dht.readHumidity(); // Read temperature as Celsius
    t = dht.readTemperature(); // Read temperature as Fahrenheit
    f = dht.readTemperature(true);
    Serial.print(F("Temp:"));
    Serial.println(t);
    Serial.print(F("Hum:"));
    Serial.println(h);
    // Controleren op juiste response
    if (isnan(h) || isnan(t) || isnan(f)) {
      Serial.println(F("Failed to read from DHT sensor!"));
      return;
    }
    //uitrekenen teperatuur 
    float hi = dht.computeHeatIndex(f, h);
    if (t > TempHigh){
       TempHigh = t;
    }
    if (t < TempLow){
      TempLow = t;
    }
    if (h > HumHigh){
      HumHigh = h;
    }
    if (h < HumLow){
      HumLow = h;
    }  
}

Bu the way, this is the edited code from the Timealarms example using an NTP server which does work:

#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h> 
#include <Time.h>
#include <TimeAlarms.h>
////////////////////////
//// Netwerk kaart settings
///////////////////////
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0E, 0xF5, 0x3E };
IPAddress ip(192,168,1,3);
IPAddress gateway(192,168,1,1);	
IPAddress subnet(255,255,255,0);
EthernetServer server(80);
EthernetClient client;
//////////////////////
//// UDP/Time Settings
//////////////////////
unsigned int localPort = 8888;  
IPAddress timeServer(129, 250, 35, 250); //pool.ntp.org
const int NTP_PACKET_SIZE= 48; // NTP time stamp is in the first 48 bytes of the message
byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets 
EthernetUDP Udp; // A UDP instance to let us send and receive packets over UDP
const  int timeZoneOffset = +1; // GMT zone;

void setup()
{
  Serial.begin(9600);
  pinMode(10, OUTPUT);            // ethernet shield uitschakelen
  digitalWrite(10, HIGH);         // zodat SPI bus vrijkomt
  delay(1000);
  Ethernet.begin(mac, ip, gateway, gateway, subnet);        // start ethernet shield
  server.begin();                 // start server
  Serial.print(F("server is Online op: "));
  Serial.println(Ethernet.localIP());  
  setSyncProvider(getNtpTime);
  while(timeStatus()== timeNotSet);
  
  // create the alarms 
  Alarm.alarmRepeat(8,30,0, MorningAlarm);  // 8:30am every day
  Alarm.alarmRepeat(17,45,0,EveningAlarm);  // 5:45pm every day 
  Alarm.alarmRepeat(dowSaturday,8,30,30,WeeklyAlarm);  // 8:30:30 every Saturday 

 
  Alarm.timerRepeat(15, Repeats);            // timer for every 15 seconds    
  Alarm.timerOnce(10, OnceOnly);             // called once after 10 seconds 
}

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

// functions to be called when an alarm triggers:
void MorningAlarm(){
  Serial.println("Alarm: - turn lights off");    
}

void EveningAlarm(){
  Serial.println("Alarm: - turn lights on");           
}

void WeeklyAlarm(){
  Serial.println("Alarm: - its Monday Morning");      
}

void ExplicitAlarm(){
  Serial.println("Alarm: - this triggers only at the given date and time");       
}

void Repeats(){
  Serial.println("15 second timer");         
}

void OnceOnly(){
  Serial.println("This timer only triggers once");  
}

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

/*-------- NTP code ----------*/

unsigned long getNtpTime()
{
 sendNTPpacket(timeServer); // send an NTP packet to a time server
 delay(1000);
 if ( Udp.parsePacket() ) {  
   // We've received a packet, read the data from it
   Udp.read(packetBuffer,NTP_PACKET_SIZE);  // read the packet into the buffer

   //the timestamp starts at byte 40 of the received packet and is four bytes,
   // or two words, long. First, esxtract the two words:

   unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
   unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);  
   // combine the four bytes (two words) into a long integer
   // this is NTP time (seconds since Jan 1 1900):
   unsigned long secsSince1900 = highWord << 16 | lowWord; 
   const unsigned long seventyYears = 2208988800UL;     
   // subtract seventy years and add the time zone:
   unsigned long epoch = secsSince1900 - seventyYears + (timeZoneOffset * 3600L);
   return epoch;
 }
 return 0;
}

// send an NTP request to the time server at the given address 
unsigned long sendNTPpacket(IPAddress& address)
{
 // set all bytes in the buffer to 0
 memset(packetBuffer, 0, NTP_PACKET_SIZE); 
 // Initialize values needed to form NTP request
 // (see URL above for details on the packets)
 packetBuffer[0] = 0b11100011;   // LI, Version, Mode
 packetBuffer[1] = 0;     // Stratum, or type of clock
 packetBuffer[2] = 6;     // Polling Interval
 packetBuffer[3] = 0xEC;  // Peer Clock Precision
 // 8 bytes of zero for Root Delay & Root Dispersion
 packetBuffer[12]  = 49; 
 packetBuffer[13]  = 0x4E;
 packetBuffer[14]  = 49;
 packetBuffer[15]  = 52;

 // all NTP fields have been given values, now
 // you can send a packet requesting a timestamp: 		   
 Udp.beginPacket(address, 123); //NTP requests are to port 123
 Udp.write(packetBuffer,NTP_PACKET_SIZE);
 Udp.endPacket(); 
}