Arduino Forum

Using Arduino => Programming Questions => Topic started by: mem on Jul 09, 2011, 12:26 pm

Title: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mem on Jul 09, 2011, 12:26 pm

Time and TimeAlarms are libraries for handling time and time based tasks on Arduino. The code can be found here (http://www.arduino.cc/playground/Code/Time). 

This thread is for help on how to use these libraries and suggestions for future improvements.

A thread specifically for discussing issues relating to updates in the beta test version can be found here (http://arduino.cc/forum/index.php/topic,66048.0.html) (that thread will be closed after the beta testing is completed.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: copet_pitik on Jul 09, 2011, 08:03 pm
First, i am noob in arduino and just tinkering arduino.

i make a clock using :
1. Arduino UNO
2. RTC DS1307
3. LCD 16*2 character

the purpose of my sketch:
1. Read Serial data VB from VB to set RTC if Serial Header is 'T'
   example : T1310258400 set RTC to July 10th 2011. 00:40:00
2. Read Serial data VB from VB to write EEPROM if Serial Header is 'I'
   example :
      I080014000045
      * then save :
      *  - 08 to EEPROM address 200 ==> alarm start hour
      *  - 00 to EEPROM address 201 ==> alarm start minute
      *  - 14 to EEPROM address 202 ==> alarm end hour
      *  - 00 to EEPROM address 203 ==> alarm end minute
      *  - 00 to EEPROM address 204 ==> alarm interval hour
      *  - 45 to EEPROM address 205 ==> alarm interval minute
      * desired output:
      * alarm ring every 45 minutes since 08.00 up to 14.00
3. Comparing RTC time and alarm data to ring the alarm

problem:
if i compare RTC time and EEPROM value and start the alarm, alarm time is late.
   example :
      alarm is set like above
      alarm ring at 08.45.26 (hh.mm.ss), my desired output : alarm ring at 08.45.00
         alarm ring every 45 minutes and approx. 25 seconds
      alarm ring at 14.14.30 (hh.mm.ss), my desired output : alarm didn't ring at that time

questions:
1. any mistakes in my sketch?
2. how to simplyfy this sketch?

Code: [Select]

#include <Time.h>
#include <TimeAlarms.h>
#include <Wire.h>
#include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t
#include <EEPROM.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(8, 7, 13, 12, 11, 10);

//RTC variable
#define TIME_MSG_LEN  11   // time sync to PC is HEADER followed by unix time_t as ten ascii digits
#define TIME_HEADER  'T'   // Header tag for serial time sync message
//===========end============

//variable for InternalSlave1() function
#define PJG_DATA 13 //the length of the alarm data
#define INT_SLAVE 'I'//alarm interval mode header
#define OTHERS 'B'//nothing
//===========end===========

//variable for EEPROMread() function
int address = 200;
byte value;
//===========end===========
void setup()
{
  Serial.begin(9600);
  lcd.begin(16,2);
  pinMode(13,OUTPUT);
  setSyncProvider(RTC.get);   // the function to get the time from the RTC
  setSyncInterval(600);
  if(timeStatus()!= timeSet)
    lcd.println("Can't sync RTC! ");
  else
    lcd.println(" Can sync RTC!  ");
  delay(1000);
  lcd.clear();
}

void loop()
{
  compareAlarmInt();
  Alarm.delay(0);
  if(Serial.available())
  {
    char header = Serial.read();
    if (header == TIME_HEADER) //ex : T1309734393
      processSyncMessage();
    else if (header == INT_SLAVE) //ex : I080012000045
      IntervalSlave1();
  }
  digitalClockDisplay();
  delay(1000);
}


/*====================read VB serial data to set RTC===================*/
void processSyncMessage()
{
  time_t pctime = 0;
  // return the time if a valid sync message is received on the serial port.
  while (Serial.available() > TIME_MSG_LEN);
  for(int i=0; i < TIME_MSG_LEN -1; i++)
  {   
    char c = Serial.read();
    if( c >= '0' && c <= '9'){   
      pctime = (10 * pctime) + (c - '0') ; // convert digits to a number   
    }
  }
  time_t t = pctime;
  RTC.set(t);
  setTime(t);
  //return;
}

//read ALARM (mode INTERVAL for SLAVE 1) from VB (Serial data) and save to EEPROM ARDUINO//
void IntervalSlave1()
{
}

/*====================COMPARING TIME data and ALARM data =======================*/
void compareAlarmInt(){
  char y = hour();
  char z = minute();
  char c = EEPROM.read (200); //hourEEPROM    ==>alarm start hour
  char d = EEPROM.read (201); //minuteEEPROM  ==>alarm start minute
  char e = EEPROM.read (202); //hourEEPROM    ==>alarm end hour
  char f = EEPROM.read (203); //minuteEEPROM  ==>alarm end minute
  if ( y >= c && z >= d && y <= e && z <= f ){
    //Serial.println("time data equal with alarm data");
    char g = EEPROM.read (204); //hourEEPROM    ==>alarm interval hour
    char h = EEPROM.read (205); //minuteEEPROM  ==>alarm interval minute
    Alarm.timerRepeat(g, h, 0, intSlave1);
  }
  else
    Serial.println("===========================");
}
/*====================INTERVAL SLAVE 1 COMMAND=================*/
void intSlave1(){
  Serial.println("bip...bipp..bippp");
}

void digitalClockDisplay()
{
  //display the clock
  //same with mem's example
}



Quote
^_^ thanks, and sorry for my english ^_^
regards,
.cop.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mem on Jul 09, 2011, 09:58 pm
coppet_pitik, if I understand the purpose of your sketch, you don't need to compare the eeprom time to the time, the TimeAlarm library does that for you.
To simplify things, try and get the sketch working without the eeprom code and without the serial messages to set the alarms. There are a number of ways to achieve that, perhaps the simplest Is to create a timer with the interval minute and two alarms - one to enable the timer at your start time and the other to disable the timer.   After you have the hard coded version working you can add the code to set the interval and the start and end alarms from the serial message.

The example sketch provided with the library shows how to create the two alarms and some timers.
You can simplify that sketch because you only need one timer. When you are satisfied that it works you can try changing the alarm times and timer durations in the code.

Then add the serial message handling. When that is working you can add code to store the alarm times in eeprom.

I hope that helps.

Michael
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: copet_pitik on Jul 10, 2011, 06:31 am
mem, thanks for your reply..
OK, i will try your suggesttion..

.cop.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: copet_pitik on Jul 11, 2011, 03:22 pm


The example sketch provided with the library shows how to create the two alarms and some timers.

Michael



mem,
the example is refers to TimeAlarmExample Sketch, didn't it?
reffering to my example i need the Alarm on:
      I080014000045
      So, the alarm start on 08.00.00
      the 2nd alarm start on 08.45.00
      the 3rd alarm start on 09.30.00
      the 4th alarm start on 10.15.00
      the 5th alarm start on 11.00.00
      ...
      the last alarm start on 14.00.00

Did you suggest me to use "Alarm.alarmRepeat or Alarm.timerOnce" to start and terminate (end) the alarm and use "Alarm.timerRepeat" to set the interval?
just wanna be sure about what i'm gonna do.
Sorry, i am kinda rough this 2 days, didn't tinkering on my UNO at all..

.cop.
 
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mem on Jul 11, 2011, 04:13 pm
Here is a (untested) fragment that shows a modified version of the TimerAlarm example with changes to turn on and off a timer that will repeat at intervals you can set.
Code: [Select]
#include <Time.h>
#include <TimeAlarms.h>

AlarmID_t repeatTimer; // the alarm id so you can change the period on the fly

void setup()
{
 
 setTime(8,29,40,1,1,10); // set time to 8:29:40am Jan 1 2010

 Alarm.alarmRepeat(8,30,0, MorningAlarm);  // 8:30am every day
 Alarm.alarmRepeat(17,45,0,EveningAlarm);  // 5:45pm every day

 // set the repeat timer for 45 minutes
 repeatTimer = Alarm.timerRepeat( 45 * SECS_PER_MIN, RepeatTask);  

}

void MorningAlarm()
{
 // turn on the repeat timer
  Alarm.enable(repeatTimer);
}

void EveningAlarm()
{
  Alarm.disable(repeatTimer);        
}

void RepeatTask()
{
  // this is called every 45 minutes if the alarm is on    
}

loop and other code goes here....


to change the value of the repeat to 60 minutes you would make this call:
 Alarm.write(repeatTimer,  60 * SECS_PER_MIN) ;  // set the repeat period to 60

I hope that gets you going in the right direction

Michael
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: copet_pitik on Jul 11, 2011, 04:39 pm


I hope that gets you going in the right direction

Michael


Michael, thanks a lot for the fragment example,

.cop.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: copet_pitik on Jul 12, 2011, 06:21 pm
mem, your sketch works great.
But, when I add your sketch to my sketch and add EEPROM library there are something wrong.
Can I place this code (below) in void loop()? not in void setup().

Code: [Select]

  Alarm.alarmRepeat(19,54,0, MorningAlarm);
  Alarm.alarmRepeat(19,55,30,EveningAlarm);   
  repeatTimer = Alarm.timerRepeat( 1 * SECS_PER_MIN, RepeatTask);


my purpose to place the code in void loop() are i can change "start, interval and stop alarm" parameters from VB anytime and save it to EEPROM.
So, if Arduino Power is OFF I don't have to set "start, interval and stop alarm" parameters.
I have tried my idea and the alarm can't be disabled.

this is the part of my sketch:

Code: [Select]

#include <Time.h>
#include <TimeAlarms.h>
#include <Wire.h> 
#include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t
#include <EEPROM.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(8, 7, 13, 12, 11, 10);

AlarmID_t doRingIntS1;

void loop()
{
  compareAlarmInt();
  Alarm.delay(0);
  ....
}

void compareAlarmInt()
{
  char c = EEPROM.read (200); //hourEEPROM    ==>1//START HOUR
  char d = EEPROM.read (201); //minuteEEPROM  ==>1//START MINUTE
  char e = EEPROM.read (202); //hourEEPROM    ==>1//STOP HOUR
  char f = EEPROM.read (203); //minuteEEPROM  ==>1//STOP MINUTE
  char g = EEPROM.read (204); //hourEEPROM    ==>1//INTERVAL HOUR
  char h = EEPROM.read (205); //minuteEEPROM  ==>1//INTERVAL MINUTE
  Alarm.timerRepeat(c, d, 0, StIntSlave1); //==start alarm mode interval slave 1
  Alarm.timerRepeat(e, f, 0, EndIntSlave1); //==End alarm mode interval slave 1
  g = g * 60;
  h = h + g;
  alarmIntervalSlave1 =  Alarm.timerRepeat( h * SECS_PER_MIN, doRingIntS1 );
}
/*====================INTERVAL ALARM SLAVE 1, START and STOP/END =================*/
void StIntSlave1(){
  Alarm.enable(alarmIntervalSlave1);
}
void EndIntSlave1(){
  Alarm.disable(alarmIntervalSlave1);
}
/*====================INTERVAL SLAVE 1 COMMAND=================*/
void doRingIntS1(){
  lcd.setCursor(0,1);
  lcd.print("bip..bipp..bip..");
  delay(3000);
  lcd.clear();
}
...
...
...


any suggestion,mem?

thanks,

.nug.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: copet_pitik on Jul 12, 2011, 08:09 pm
First important bug:
timerRepeat and alarmRepeat ==> my fault
:smiley-sad-blue: :smiley-sad-blue: :smiley-sad-blue:
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mem on Jul 12, 2011, 08:31 pm
Hi copet_pitik,

What is the purpose of the campareAlarmInt function?

If you want to save alarm values in eeprom so you they can be read when starting up then you don't need to compare.
Read the eeprom values in setup to set the alarms.
In loop you can check for serial messages and if you get a request to change an an alarm value you can write that to eeprom and update the alarm value.

As I suggested earlier, ignore the eeprom functionality for now.

First get the the alarms responding to serial commands. When that is fully tested and working it should be easy to add the eeprom code.

Michael


Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: copet_pitik on Jul 13, 2011, 09:06 am

What is the purpose of the campareAlarmInt function?


my purpose for compareAlarmInt is to scan the alarm value in loop function.


If you want to save alarm values in eeprom so you they can be read when starting up then you don't need to compare.
Read the eeprom values in setup to set the alarms.
In loop you can check for serial messages and if you get a request to change an an alarm value you can write that to eeprom and update the alarm value.

mem,
when I send serial messages, then Arduino will reset automatically?

thanks for your guidance..

.nug.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mem on Jul 13, 2011, 12:07 pm
Quote
my purpose for compareAlarmInt is to scan the alarm value in loop function.

That does not describe a purpose, it says how you want to achieve a purpose but not why.
What do you want to achieve when you scan the alarm value in loop?

Quote
when I send serial messages, then Arduino will reset automatically?

You said above that you wanted to send VB messages to set the alarm. If you need help with aspects of your application that are not specific to the TimeAlarms library then its best to start a new thread so that the content of this one is focused on specific help with TimeAlarms.

I suggest your create a new thread and post a link  here so I and others interested in your application can help.

Michael


Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: copet_pitik on Jul 13, 2011, 05:22 pm
Thanks for your advice, mem.
.nug.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mem on Jul 13, 2011, 06:08 pm
happy to help. If you have questions on the TimerAlarms library ask here. Post a link to a new thread if you have other questions on your application.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: viknet on Jul 21, 2011, 01:31 pm
for those needing a full solution for scheduling daily / weekly start/stop of output, I started a new thread with my project.
http://arduino.cc/forum/index.php/topic,67127.0.html

It heavily use the timealarm lib albeit a bit modified.

regards
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: copet_pitik on Jul 22, 2011, 12:27 pm

I suggest your create a new thread and post a link  here so I and others interested in your application can help.



mem,here is my next question about my project, hope you can help
http://arduino.cc/forum/index.php/topic,67289.msg494141.html#msg494141
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mem on Jul 22, 2011, 06:46 pm
No errors were reported with the the beta code so the playground download has been updated.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: viknet on Jul 22, 2011, 09:42 pm
Check my project at http://arduino.cc/forum/index.php/topic,67127.0.html

I javel thé sketch and à sérial interface also have a jquery web interface
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: alvarojusten on Jul 25, 2011, 06:09 am


Time and TimeAlarms are libraries for handling time and time based tasks on Arduino. The code can be found here (http://www.arduino.cc/playground/Code/Time). 

This thread is for help on how to use these libraries and suggestions for future improvements.

A thread specifically for discussing issues relating to updates in the beta test version can be found here (http://arduino.cc/forum/index.php/topic,66048.0.html) (that thread will be closed after the beta testing is completed.



Hello mem,
I needed to use DS1307 Real-Time Clock on a project and saw the Time library, but I thought it was too big for what I needed (just to know day, month, year, hour, minute and second from DS1307), so I decided to create a new, simple library to achieve this task and its code is at GitHub:

https://github.com/turicas/DS1307

I think we should integrate it, maybe creating a "driver interface" (just some conventions) so we can create drivers for many RTC chips and use the same code. What do you think?

Other thing I think that should be changed in Time library is the namespace of functions. Maybe using Time.hour(), Time.day() etc. instead of directly hour(), day() etc.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mem on Jul 25, 2011, 02:19 pm


Hello mem,
I needed to use DS1307 Real-Time Clock on a project and saw the Time library, but I thought it was too big for what I needed (just to know day, month, year, hour, minute and second from DS1307), so I decided to create a new, simple library to achieve this task and its code is at GitHub:

https://github.com/turicas/DS1307

I think we should integrate it, maybe creating a "driver interface" (just some conventions) so we can create drivers for many RTC chips and use the same code. What do you think?

Other thing I think that should be changed in Time library is the namespace of functions. Maybe using Time.hour(), Time.day() etc. instead of directly hour(), day() etc.



Hi alvarojusten

Thank you for sharing your library. I have seen many  DS1037 Arduino libraries and yours is one of the simplest (that's  a compliment).  It does use less flash memory than the Time library but it actually seems to use more data (your sketch  uses 540 bytes of RAM, the Time library code posted below uses 482 bytes of RAM).

Code: [Select]
/*
*  A simple sketch to display time from a DS1307 RTC
*
*/

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

char dateTime[20];

void setup()  {
  Serial.begin(9600);     
}

void loop()
{
   setTime(RTC.get());
   sprintf(dateTime, "%4d-%02d-%02d %02d:%02d:%02d", year(),
            month(), day(), hour(),minute(), second()) ;
    Serial.print(dateTime);
    Serial.print(" - day of week: ");
    Serial.println(dayStr(weekday()));

   delay(1000);
}


Here are some advantage of using the Time library version:
-   You can easily calculate the difference between two times
-   The time format is based on a standard that almost every programming platform can handle
-   The same sketch code can be used with a selection of time sources such as RTC, NTP( internet time standards), Radio Clocks, GPS …
-   You can use the TimeAlarms library to add timers and time of day alarms.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: copet_pitik on Aug 06, 2011, 01:56 pm
Hi [again], Mem.

how to convert now() function (=>unixtime) to character array (char[11])?Is it possible to do?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mem on Aug 06, 2011, 07:20 pm
Many C compilers have a function named ctime that produces a date string but I don't think its available with the arduino tools. I have always used multiple print statements to display the data, is there a reason you can't do that for your application?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: robtillaart on Aug 06, 2011, 07:34 pm

ctime is not found in - http://www.nongnu.org/avr-libc/user-manual/index.html -

maybe this link helps - http://www.jbox.dk/sanos/source/lib/time.c.html -
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mem on Aug 06, 2011, 07:45 pm
Rob, did you try to use it in the Arduino IDE?
If so, a brief example would be useful.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: robtillaart on Aug 06, 2011, 08:47 pm
No,

however I did use the RTC lib for the DS1307 - - https://github.com/adafruit/RTClib -  It includes a DateTime Class that has all needed to implement a  time2string(...) function
Note DateTime is year 2000 based, the essential code is in the DateTime constructor that can be transformend quite easily, see below:

Code: [Select]

void setup()
{
  Serial.begin(115200);
  Serial.println("UnixTime simulator :) ");
}

void loop()
{
  char buffer[20];
  time2string(millis(), buffer);
  Serial.print(millis());
  Serial.print(" ==>  ");
  Serial.println(buffer);
}

uint8_t daysInMonth [] = { 31,28,31,30,31,30,31,31,30,31,30,31 };

void time2string(unsigned long t, char *buf)
{
  uint8_t yOff, m, d, hh, mm, ss;

  ss = t % 60;
  t /= 60;
  mm = t % 60;
  t /= 60;
  hh = t % 24;
  uint16_t days = t / 24;
  uint8_t leap;
  for (yOff = 0; ; ++yOff) {
        leap = yOff % 4 == 0;
        if (days < 365 + leap)
            break;
        days -= 365 + leap;
  }
  for (m = 1; ; ++m) {
    uint8_t daysPerMonth = daysInMonth[ m - 1];
    if (leap && m == 2)
      ++daysPerMonth;
    if (days < daysPerMonth)
        break;
    days -= daysPerMonth;
  }
  d = days + 1;
  sprintf(buf,"%4d-%02d-%02d %02d:%02d:%02d", 1970+yOff, m,d, hh,mm,ss);
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: copet_pitik on Aug 06, 2011, 09:04 pm
thanks Rob, Mem..

Quote
Many C compilers have a function named ctime that produces a date string but I don't think its available with the arduino tools. I have always used multiple print statements to display the data, is there a reason you can't do that for your application?

My Goal is sending unixtime via Wireless, then I have data in char array (char[11])
so when i try to send data unixtime which it is unsigned long, the compiler give error message:
Code: [Select]
incompatible types in assignment of 'time_t' to 'char [11]'

Rob, I use Mem's library (Time, TimeAlarm, DS1307RTC)..Any suggestion how to do it for DS1307RTC library?thanks anyway for the help.

thanks a lot.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: robtillaart on Aug 06, 2011, 09:21 pm
do you mean some thing like this?

Code: [Select]

#include "stdlib.h"

void setup()
{
 Serial.begin(115200);
 char buffer[11];
 unsigned long unixtime=1234567890L;  // L for long
 ltoa(unixtime, buffer, 10);
 Serial.println(buffer);
}

void loop(){}

(code not tested)

see - http://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html - search for ltoa

UPDATE
-- added void before loop()
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: copet_pitik on Aug 06, 2011, 10:07 pm


do you mean some thing like this?

Code: [Select]

#include "stdlib.h"

void setup()
{
  Serial.begin(115200);
  char buffer[11];
  unsigned long unixtime=1234567890L;  // L for long
  ltoa(unixtime, buffer, 10);
  Serial.println(buffer);
}

loop(){}

(code not tested)

see - http://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html - search for ltoa


FOOL me, i tried it, but i didn't print the buffer..
Thanks, a lot..i'll try tomorrow. now, 3.05am..here..need a sleep..aha!
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: robtillaart on Aug 07, 2011, 12:51 am
you need to add void before loop(){}

allready patched in posting above.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: copet_pitik on Aug 07, 2011, 08:59 am

you need to add void before loop(){}

allready patched in posting above.


the code just works..thanks, rob..(http://static.kaskus.us/images/smilies/jempol2.gif)
ltoa and atol will be my new friends..LOL..

(http://www.indowebster.web.id/images/smilies/jeanovea/semangat.gif)
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: robtillaart on Aug 07, 2011, 10:35 am
welcome,

surf one evening over the - http://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html - site and you learn thousand new possibilities ;)
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: copet_pitik on Aug 20, 2011, 09:05 pm
How to check alarm time on timeAlarm library?
it is possible to know the "alarm ID" is enable  or disable?
I got this code from the old forum
Code: [Select]
void checkAlarm(){

  showAlarmTime(ID1);
  showAlarmTime(ID2);
  showAlarmTime(ID3);
  showAlarmTime(ID4);
  showAlarmTime(ID5);
  showAlarmTime(ID6);

  Serial.println("----------------------------------------------------");
}//checkAlarm

void showAlarmTime(AlarmID_t id){
  time_t alarmTime = Alarm.read(id);
  if(alarmTime != 0)
  {
    if( alarmTime <= SECS_PER_DAY) 
      Serial.print(" repeat alarm with ID ");
    else 
      Serial.print(" once only alarm with ID  ");
    Serial.print(id, DEC);   
    Serial.print(" set for ");
    digitalClockDisplay1(alarmTime);
  }
}//showAlarmTime


but, i guess those code doesn't show the alarm is disabled or enabled.
thanks for any suggestions.
regards,
nug.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Aug 21, 2011, 04:18 pm
Quote
it is possible to know the "alarm ID" is enable  or disable?

How does the alarm become enabled or disabled? Your code does that. Make your code remember that status it set the alarm to. You need to keep track of the alarm IDs, so a structure that linked alarm ID and status should be easy to implement.

Code: [Select]
struct alarmData
{
   int alarmID;
   bool armed;
};
typedef struct alarmData AlarmData;


Code: [Select]
AlarmData ad;
ad.alarmID = ?; // Assign the alarm ID
ad.armed = false; // It is not enabled


Whenever you change state, set the structure member, too.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: bill2009 on Aug 31, 2011, 12:31 am
Hi, I've been using the Time library for a while just based on the arduinos timers. My sketch has functions to setTime() and uses now() to get it.  I sometimes want to set the time to something specific for testing but having the RTC time as default is best.
I've picked some code out of the examples to get the time from the RTC when the sketch starts.
Code: [Select]
 setSyncProvider(RTC.get);   // the function to get the time from the RTC
 if(timeStatus()!= timeSet) {
    Serial.println("Unable to sync with the RTC");
 }
 else{
   Serial.println("RTC has set the system time");      
 }
 digitalClockDisplay(now());     cout<<endl;


If I later call setTime() with my test time it seems to stay set but I worry that some synch function might bite me when I call now() - will it?  what it i don't setSyncProvider - can i get the RTC time into the library without doing that?

Also, thank you for the library - it's been a great help.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: tagalog88 on Sep 11, 2011, 04:36 am
I didn't find this thread until after I already posted here:
http://arduino.cc/forum/index.php/topic,71970.msg538464.html#msg538464 (http://arduino.cc/forum/index.php/topic,71970.msg538464.html#msg538464)

I'm trying to figure out how Time handles the situation when millis() rolls over but I'm not getting it.  I'd love a nudge in the right direction.

Cheers!
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: willem4ever on Sep 11, 2011, 12:36 pm
Hi,

I'm trying to use the Time library with arduino 1.0-beta4  for OSX (library is located at ~willem/Documents/Arduino/Libraries/Time) when I compile I get

UdpNtpClient_WE.cpp:1:18: error: Time.h: No such file or directory

I guess something has changed for IDE 1.0 (beta) .... who knows the solution ?

Cheers, Willem.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: tigro on Sep 15, 2011, 02:04 pm
Hi all,

I'm using the time library for my home energy monitoring project. In this project, I count the pulses coming from my electricity, gas and water meter. I also read out a  temp/humidity sensor (SHT15) located in my garage.
Each time a change in one of the "sensors" occurs (i.e pulse or value change from temp/humidity sensor) , a UDP message with a small XML string is sent to a monitoring system. Below is an example of such a message (when a value change occurs for the humidity sensor) :
Code: [Select]

<e>
<s id="6" vChMSRo="0" vChMS="1599330" vChDT="2011-09-15T10:06:01" val="487" />
</e>

Explanation :
id = sensor identification
vChMSRo = value change millis rollover (I count the number of times the millis() rolled over since start-up)
vChMS = number of milliseconds at which the value change occurred
vChDT = date/time at which the value change occurred
val = the actual value

And below is one for a pulse counter (I'm using interrupt service routines for counting pulses) :
Code: [Select]

<e>
<s id="1" pIDRo="0" pID="3" pStartMSRo="0" pStartMS="8162174" pStartDT="2011-09-15T11:55:27" pDurMS="138" pIntMS="0" state="0" />
</e>

Explanation :
id = sensor identification
pIDRo = number of times the pulse ID rolled over
pID = pulse ID
pStartMSRo = number of times the millis() rolled over at the time the pulse started
pStartMS = millis() value at the time the pulse started
pStartDT = date/time the pulse started
pDurMS = duration of the pulse in ms
pIntMS = interval between this pulse and the previous pulse (in ms)
state = current state of the pulse

The XML string contains - among other info - the date and time at which the event occurred.
For each (pulse) sensor, the date/time is stored in a time object.
For reporting, I'm using the following function to convert the time object to a date/time string :
Code: [Select]

char* XMLDateTime(time_t t)
{
   char chrDT[21];
   PString strDT(chrDT, sizeof(chrDT));
 
   strDT.print(year(t));
   strDT.print("-");
   if (month(t) < 10)
   {
      strDT.print("0");
   };
   strDT.print(month(t));
   strDT.print("-");
   if (day(t) < 10)
   {
      strDT.print("0");
   };
   strDT.print(day(t));
   strDT.print("T");
   if (hour(t) < 10)
   {
      strDT.print("0");
   };
   strDT.print(hour(t));
   strDT.print(":");
   if (minute(t) < 10)
   {
      strDT.print("0");
   };
   strDT.print(minute(t));
   strDT.print(":");
   if (second(t) < 10)
   {
      strDT.print("0");
   };
   strDT.print(second(t));
   strDT.print("Z");
   return chrDT;
}



The problem :
Very frequently I get crappy output in the date/time string part, like this :
Code: [Select]

<s id="5" vChMSRo="0" vChMS="8462268" vChDT="2011-09-15 !Ó" val="243" />
<s id="6" vChMSRo="0" vChMS="8433906" vChDT="2011-09!ÓS" val="507" />


It seems that sometimes a kind of buffer overflow occurs. Initially, I used the String object, but that made it even worse! (PString is a buffer overflow save string object).
Could you please check what could be the reason for this strange output?

Kind regards,

Bart.



Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mem on Sep 19, 2011, 02:00 pm

Hi,

I'm trying to use the Time library with arduino 1.0-beta4  for OSX (library is located at ~willem/Documents/Arduino/Libraries/Time) when I compile I get

UdpNtpClient_WE.cpp:1:18: error: Time.h: No such file or directory

I guess something has changed for IDE 1.0 (beta) .... who knows the solution ?

Cheers, Willem.

Here is an NTP code for Arduino 1.0:
Code: [Select]
/*
* Time_NTP sketch
* Example showing time sync to NTP time source
*
* This sketch uses the Time library
* and the Arduino 1.0 Ethernet library
*/

#include <Time.h>
#include <SPI.h>         // needed for Arduino versions later than 0018
#include <Ethernet.h>
#include <EthernetUDP.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 1, 44 }; // set this to a valid IP address (or use DHCP)

unsigned int localPort = 8888;      // local port to listen for UDP packets

IPAddress timeServer(192, 43, 244, 18); // time.nist.gov NTP server

const int NTP_PACKET_SIZE= 48; // NTP time stamp is in first 48 bytes of message
byte packetBuffer[ NTP_PACKET_SIZE]; // buffer to hold incoming/outgoing packets

time_t prevDisplay = 0;    // when the digital clock was displayed

// A UDP instance to let us send and receive packets over UDP
EthernetUDP Udp;

void setup()
{
  Serial.begin(9600);
  Ethernet.begin(mac,ip);
  Udp.begin(localPort);
  Serial.println("waiting for sync");
  setSyncProvider(getNtpTime);
  while(timeStatus()== timeNotSet)
     ; // wait until the time is set by the sync provider
}

void loop()
{
  if( now() != prevDisplay)   //update the display only if the time has changed
  {
    prevDisplay = now();
    digitalClockDisplay();
  }
}

void digitalClockDisplay(){
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print(" ");
  Serial.print(dayStr(weekday()));
  Serial.print(" ");
  Serial.print(day());
  Serial.print(" ");
  Serial.print(monthShortStr(month()));
  Serial.print(" ");
  Serial.print(year());
  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);
}

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

unsigned long getNtpTime()
{
  sendNTPpacket(timeServer); // send an NTP packet to a time server
  delay(1000);
  if ( Udp.parsePacket() ) {
     Udp.read(packetBuffer,NTP_PACKET_SIZE);  // read packet into buffer


     //the timestamp starts at byte 40, convert four bytes into a long integer
     unsigned long hi = word(packetBuffer[40], packetBuffer[41]);
     unsigned long low = word(packetBuffer[42], packetBuffer[43]);
     // this is NTP time (seconds since Jan 1 1900
     unsigned long secsSince1900 = hi << 16 | low; 
     // Unix time starts on Jan 1 1970
     const unsigned long seventyYears = 2208988800UL;     
     unsigned long epoch = secsSince1900 - seventyYears;  // subtract 70 years
     return epoch;
  }
  return 0; // return 0 if unable to get the time
}

// send an NTP request to the time server at the given address
unsigned long sendNTPpacket(IPAddress address)
{
  memset(packetBuffer, 0, NTP_PACKET_SIZE);  // set all bytes in the buffer to 0

  // Initialize values needed to form NTP request
  packetBuffer[0] = B11100011;   // LI, Version, Mode
  packetBuffer[1] = 0;     // Stratum
  packetBuffer[2] = 6;     // Max Interval between messages in seconds
  packetBuffer[3] = 0xEC;  // Clock Precision
  // bytes 4 - 11 are for Root Delay and Dispersion and were set to 0 by memset
  packetBuffer[12]  = 49;  // four-byte reference ID identifying
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52;

  // send the packet requesting a timestamp:
  Udp.beginPacket(address, 123); //NTP requests are to port 123
  Udp.write(packetBuffer,NTP_PACKET_SIZE);
  Udp.endPacket();
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mem on Sep 19, 2011, 02:19 pm

Hi all,

I'm using the time library for my home energy monitoring project.
The problem :
Very frequently I get crappy output in the date/time string part, like this :

It seems that sometimes a kind of buffer overflow occurs. Initially, I used the String object, but that made it even worse! (PString is a buffer overflow save string object).
Could you please check what could be the reason for this strange output?

Kind regards,

Bart.


Bart,
You can check if the problem is due to the chrDT buffer overflowing by testing with a hard coded string of the correct length for the date.
If you still have the problem this is probably not a Time library issue and if that is the case then best to move the discussion to a new thread.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: viknet on Sep 25, 2011, 12:25 am
hello there :-)

back from testing my code concerning a web enabled programmer you can try it here :

http://sprinkler.zapto.org/arduinoJqueryUI.html
user/password    viknet/viknet

mem,  there (as always I think) is two bug I had to correct in your library:
in the function updateNextTrigger,

I removed the check if next trigger is not yet in the future:
if the check is already in the future but you just changed the alarm to something else, the updatetrigger won't be effective immediately


I also change the write function to :
Code: [Select]
if(isAllocated(ID))
      {
        Alarm[ID].value = value;
        Alarm[ID].Mode.alarmType=period;   
        if (value!=dtINVALID_TIME)
          enable(ID);
        else
          free(ID);
      } 


because trying to set the alarm to 0 was leaving alarm in a strange state before.

all in all I am more and more convinced that 0 should be treated as a valid alarm value meaning 0:00:00 today, the main reason for that when setting an alarm to 24:00:00 (which currently work) if you read the value and apply the usual hour() minute() second() it reply 00:00:00 which is kind of wrong.

To avoid this I disabled the possibility to set an alarm at midnight : 00:00:00 and 24:00:00 are not valid time in my project :-)
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Redcap on Nov 18, 2011, 01:35 pm
Mem/Michael,
I wasn't 100% sure how to set the time, so much thanks for the code snippet/s :)

- Red
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: joe73 on Nov 19, 2011, 02:30 pm
Hello
My name is Joe
I have made clock from this page  "http://www.vonnieda.org/tc18"  but it doesn't have alarm,so I would like to add it.
This is first time for me to do something with arduino,can someone add alarm part for clock sketch for me please.

Im attaching sketch file

Thanks
Title: Convert UTC to local time
Post by: ninja2 on Nov 27, 2011, 12:49 am
I need to convert UTC time (from my LS00031 GPS unit) to local time (i.e +10.5 hours). Sure I could code this but I expect this has been done many times before. A pointer to existing code or library call would be much appreciated. TIA
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: tmdrake on Dec 05, 2011, 11:16 am
Okay, it apears the GPS synch isn't working.

Looked like part of the sample code is not finished?
Code: [Select]

time_t gpsTimeSync(){
  //  returns time if avail from gps, else returns 0
  unsigned long fix_age = 0 ;
  gps.get_datetime(NULL, NULL, &fix_age);
  unsigned long time_since_last_fix;
  if(fix_age < 1000)
    return gpsTimeToArduinoTime(); // return time only if updated recently by gps 
  return 0;
}


Always returns False.

After commenting out a few lines...
Code: [Select]

time_t gpsTimeSync(){
  //  returns time if avail from gps, else returns 0
  unsigned long fix_age = 0 ;
  gps.get_datetime(NULL, NULL, &fix_age);
  //unsigned long time_since_last_fix;
  //if(fix_age < 1000)
    return gpsTimeToArduinoTime(); // return time only if updated recently by gps 
  //return 0;
}


Seems to work...took a while before I got a synch....?

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: ninja2 on Dec 05, 2011, 11:59 am
This is covering the exact issue I'm dealing with. I commented out the same code around "fix_age" and had some success, but not as much as you ... have a look here: http://arduino.cc/forum/index.php/topic,81175.msg612786.html#msg612786 (http://arduino.cc/forum/index.php/topic,81175.msg612786.html#msg612786)

I figured "fix_age" wasn't working, so commented it out, but now I'm getting same time reported every time it starts (7:37:12 8 Jan 2000 from memory). I know the GPS is working as I've got another program that reads from it just fine, so I'm pretty sure the problem is in the way I'm using timeGPS, or with timeGPS itself.

I'd really like to nail this one ...!

PS: you say it took a while before you got synch ... can you estimate how long that was (a few secs, or mins or longer?)
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Dittothat on Dec 12, 2011, 11:25 pm
Hi,

I am having a problem compiling a sketch in Arduino 1.0 that compiled and uploaded just fine in Arduino 23. Any suggestions on how I can fix these errors:

C:\Arduino\arduino-1.0\libraries\TimeAlarms\TimeAlarms.cpp:25:22: error: WProgram.h: No such file or directory
C:\Arduino\arduino-1.0\libraries\TimeAlarms\TimeAlarms.cpp: In member function 'void TimeAlarmsClass::delay(long unsigned int)':
C:\Arduino\arduino-1.0\libraries\TimeAlarms\TimeAlarms.cpp:256: error: 'millis' was not declared in this scope

Is anyone else having this trouble?

Thanks,
Jeff
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: ninja2 on Dec 12, 2011, 11:59 pm
you need to read through "Readme.txt" file on the downlaod opage for Arduino 1.0. It explains a few changes that you will need to make, such as replacing "Wprogram.h" with "Arduino.h" in you programs and any libraries using it.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: bill2009 on Dec 13, 2011, 02:34 pm
There may be a new version of the library posted to correct the problem - look wherever you got it.  If not, find the file C:\Arduino\arduino-1.0\libraries\TimeAlarms\TimeAlarms.cpp and open it with notepad.  At line 25 you'll find the reference to Wprogram.h which you can change to Arduino.h and save.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Dittothat on Dec 13, 2011, 04:41 pm
Yes, thank you. That worked fine. Just change the reference from Wprogram.h to Arduino.h and all is well again.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Happyworker on Dec 16, 2011, 04:30 am
Hi there,
I'm making a self watering system, that has a reed switch that indicates if the water level is low, a moisture sensor for the soil, and a battery voltmeter to let me know when I should recharge my batteries, and a relay to turn on the pump.
Here is what I want to do.


I've been trying to work with the Time library to do the following:


I've taken out the time code from the sketch because I wanted to show that this working how I want it, just not with respect to the time I'm looking for.


Just getting a little frustrated with all these times.  Any help or suggestions would be greatly appreciated.


Code: [Select]
/*
* Gardening Project v1.2
* Combining the capacitive sensor, moisture sensor, pump and led indicator.
* Reading how much water is in the container.
* Reading how much moisture is in the ground.
* Pumping water if moisture is dry.
* LED
* Red - low battery , blink

*/
#include <Bounce.h>
#include <Time.h>
#include <TimeAlarms.h>

#define LED 9  // LED on pin 9
#define SWITCH 10  // Defines the Reed switch on digital pin 10
int reed_val = 0;  // used to store the input of the reed switch
Bounce bouncer = Bounce( SWITCH,10 );

//  Volt monitoring
  int batteryPin = 1;
  float vout = 0;
  int value = 0;
  float R1 = 991;    // !! resistance of R1 !!
  float R2 = 995;     // !! resistance of R2 !!
  float vin = 0;

// Moisture Sensor
  int moistureSensor = 5;  // Sensor pin 5, other pin connected to GRN through a 10k resistor
  int moisture_val;  // Storing the current value of the Sensor pin
  int waterpump = 7;  // Initializing pin 7 for waterpump


void setup()  {
  Serial.begin(9600);
  pinMode(SWITCH, INPUT);  // Defines the switch as an input
  digitalWrite(SWITCH, HIGH);
  pinMode(LED,OUTPUT);  // LED as an output
  pinMode(waterpump,OUTPUT);  // Setting waterpump to output
  digitalWrite(waterpump,LOW);  // waterpump off

 
}

void loop()  {
 
  analogReference(EXTERNAL);
  bouncer.update();
  int reed_val= bouncer.read();
  moisture_val = analogRead(moistureSensor);
 
  // Volt Monitoring
  value = analogRead(batteryPin);
  vout= (value * 5)/1024.0;  //voltage coming out of the voltage divider
  vin = vout / (R2/(R1+R2));  //voltage to display


  // Debugging with LCD
  Serial.print("V: ");  // Print out V:
  Serial.println(vin);  // This is where the number of volts are displayed
  Serial.print("M: ");
  Serial.println(moisture_val);
  Serial.print("Reed: ");
  Serial.print(reed_val);
  delay(100);

  if (vin < 7.0)  {
    digitalWrite(waterpump,LOW);
    digitalWrite(LED,HIGH);  // LED turns on
    delay(200);
    digitalWrite(LED,LOW);
    delay(200);
}

// Reed Switch monitoring

  if (reed_val==HIGH)  {
    Serial.println("Fill Water");
    digitalWrite(waterpump,LOW);
    digitalWrite(LED,HIGH);
    delay(200);
    digitalWrite(LED,LOW);
    delay(200);
   
  }


  // Check whether input is LOW (switch closed)
  if (moisture_val < 900 && reed_val==LOW)  {
    Serial.println ("Turning on pump");   // Debugging or adding add to LCD
    digitalWrite(waterpump,HIGH);  // waterpump on
    delay(5000);
   
   
  }
  digitalWrite(waterpump,LOW);

 
  }

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Dec 16, 2011, 03:26 pm
I don't see that you need the Time or TimeAlarm libraries at all.

What you want to do can be done with a pencil and paper (variables on the Arduino) and a watch/clock (the millis() function on the Arduino).

On each pass through loop, see if it is time to check the battery level. If it is, check the battery level, and set the lastChecked time to now.

See if it is time to turn the water on. If it is, turn the water on and set the lastWaterOn time to now.

Do the same for moisture reading.

The 3 day pause affects everything? The plant dries out and dies during that 3 days, and that's OK? The battery does dead in that 3 days, and that's OK?

If you turn the system off for 3 days (i.e. do nothing in that time) and then check the water level, and it is fine, so you turn off for three days again, it could take a long time before you check the battery level. So, be careful that you check everything before going into do-nothing-for-three days mode.

Frankly, I think you have some contradictory requirements, which might explain your difficulties implementing them.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Happyworker on Dec 18, 2011, 07:37 pm
Thanks for your help PaulS.

Are you suggesting not to use the Time library at all?  Instead use  millis() ?
One of the reasons I would like to use the Time library is due to the draw of mA.  If I use the code without the Time library I'm drawing about 30mA, then when the relay turns on it uses up to 90mA.
If I'm counting using the Time library I seem to be only using 20mA while it's counting, then of course it uses the same 90mA when the relay kicks in.

My thought was that as long as I'm checking the battery every 5 minutes or so, if the battery drops below 7 volts, I will be notified by a blinking LED and go and charge it.  Since this is outside of the 3 day pause, i would be notified at least within 5 minutes and not have to wait for a full 3 days before I found out.

The plant is a palm and it's winter...so I doubt the plant is going to completely dry out in 3 days, plus I figured this should save battery power.  I can change the amount of time to check later if I find it drying out too fast.  I understand what you're saying about checking every three days, perhaps I should start with every day to check. 

Battery check - every 5 minutes
Waterlevel check - once every day
Moisture check - once every day

Cheers




Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Dec 18, 2011, 11:30 pm
So, you want the Time library to wake the Arduino every 5 minutes

Check the battery level and increment a counter for the number of times the timer has disturbed your sleep.

If the battery voltage is low, stay awake, blinking the LED.

If the counter hits some value, check for the need for water. If it needs watering, stay awake and water the plant. Reset the counter when done.

Go back to sleep. Repeat when the timer goes off again.

Watering the plant should be completed in 5 minutes, so go back to sleep at the 5 minute mark, to get back on the 5 minute sleep/wake cycle.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Happyworker on Dec 20, 2011, 06:51 am
Yes , I want to wake the Arduino every 5 minutes to check the battery and water level.
Not sure what you mean about incrementing a counter for the number of times the timer has disturbed you sleep?
Yes, stay awake and blink the LED if the voltage is low. 
Wake the Arduino every 24 hours and check if the moisture value is below 900 (900 is wet soil).  If it needs watering, turn on pump for 5 seconds, then wait 5 seconds before reading the value again.  If it needs watering, turn on pump for another 5 seconds, then wait 5 seconds before reading value again.  Continue this procedure until the value is above 900.

Thanks again, I appreciate the help.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Dec 20, 2011, 01:26 pm
The Arduino starts. It does some stuff, and goes to sleep. 5 minutes later, the alarm goes off. That's 1. It does some stuff, and goes to sleep. 5 minutes later, the alarm goes off. That's 2. It does some stuff, and goes to sleep. 5 minutes later, the alarm goes off. That's 3...

That is counting. When the counter gets to 12, that's 1 hour. When it gets to 288, that's 1 day.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Happyworker on Dec 21, 2011, 08:47 am
Thanks for all your help.
I have it working as you suggested (sort of).
The one thing that has me a bit stumped right now is that I can't seem to get the waterpump to turn on and off every 5 seconds (while it's within the Water (); function) so that it can re-check the moisture value and the reed switch value.  
I have listed the code that I have so far.
You'll notice that I have the "Battery" function set to run every 5 seconds ( this is for testing purposes only).  Normally I will have this set for
Code: [Select]
Alarm.timerRepeat(0,5,0,Battery);
The Counter == 5 in the loop is also for testing purposes only.  Normally this would be set as you suggested.
Code: [Select]
if (Counter == 12)  {
   Water();
   Counter = 0;
 }





Code: [Select]
/*
* Gardening Project v1.2.3
* Combining the capacitive sensor, moisture sensor, pump and led indicator.
* Reading how much water is in the container.
* Reading how much moisture is in the ground.
* Pumping water if moisture is dry.
* LED
* Red - low battery , blink

*/
#include <Bounce.h>
#include <Time.h>
#include <TimeAlarms.h>
#define LED 9  // LED on pin 9
#define SWITCH 10  // Defines the Reed switch on digital pin 10

int reed_val = 0;  // used to store the input of the reed switch
Bounce bouncer = Bounce( SWITCH,10 );

int Counter = 0;  // Set counter
int waterCounter = 0;  // Set watering counter

//  Volt monitoring
 int batteryPin = 1;
 float vout = 0;
 int value = 0;
 float R1 = 991;    // !! resistance of R1 !!
 float R2 = 995;     // !! resistance of R2 !!
 float vin = 0;

// Moisture Sensor
 int moistureSensor = 5;  // Sensor pin 5, other pin connected to GRN through a 10k resistor
 int moisture_val;  // Storing the current value of the Sensor pin
 int waterpump = 7;  // Initializing pin 7 for waterpump


void setup()  {
 Serial.begin(9600);
 pinMode(SWITCH, INPUT);  // Defines the switch as an input
 digitalWrite(SWITCH, HIGH);
 pinMode(LED,OUTPUT);  // LED as an output
 pinMode(waterpump,OUTPUT);  // Setting waterpump to output
 digitalWrite(waterpump,LOW);  // waterpump off
 // Time
 setTime(0,0,0,13,12,11);
 Alarm.timerRepeat(5,Battery);

}

void loop()  {
 // Display the countdown timer
 digitalClockDisplay();
 Alarm.delay(1000); // wait one second between clock display
 
 if (Counter == 5)  {
   Water();
   Counter = 0;
 }
 
}

// Start of Functions

 void Water()  {
   
 analogReference(EXTERNAL);
 bouncer.update();
 int reed_val= bouncer.read();
 moisture_val = analogRead(moistureSensor);
 Serial.print("M: ");
 Serial.println(moisture_val);
 // Check whether input is LOW (switch closed)
 if (moisture_val < 900 && reed_val==LOW)  {
   Serial.println ("Turning on pump");   // Debugging or adding add to LCD
   digitalWrite(waterpump,HIGH);  // waterpump on
   Alarm.delay(5000);
   bouncer.update();
   int reed_val= bouncer.read();
   moisture_val = analogRead(moistureSensor);
 
   if (reed_val==HIGH)  {
     return;
   }
 }
 }
 
 void Battery()  {
 // Volt Monitoring
 analogReference(EXTERNAL);
 value = analogRead(batteryPin);
 vout= (value * 5)/1024.0;  //voltage coming out of the voltage divider
 vin = vout / (R2/(R1+R2));  //voltage to display
 while (vin < 7.0)  {
   digitalWrite(waterpump,LOW);
   digitalWrite(LED,HIGH);  // LED turns on
   Alarm.delay(200);
   digitalWrite(LED,LOW);
   Alarm.delay(200);  
 }
 // Debugging with LCD
 Serial.print("V: ");  // Print out V:
 Serial.println(vin);  // This is where the number of volts are displayed
 
 // Reed Switch monitoring
 bouncer.update();
 int reed_val= bouncer.read();
 while (reed_val==HIGH)  {
   Serial.println("Fill Water");
   digitalWrite(waterpump,LOW);
   digitalWrite(LED,HIGH);
   Alarm.delay(200);
   digitalWrite(LED,LOW);
   Alarm.delay(200);
   bouncer.update();
   int reed_val= bouncer.read();
   if (reed_val==LOW)  {
     return;
   }
 }
 Counter++;
 
 }
 
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);
 }


Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Dec 21, 2011, 12:46 pm
Apparently you do know how to use the Serial.print() function to print values. Use it to print messages, too. How often does Battery() get called. What is the value of Counter in loop?

I don't see anything in your code that puts the Arduino to sleep between Alarm calls to Battery.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mmoottuuss on Dec 21, 2011, 02:40 pm
Hello,

Is there any incompatibility between these libraries?
#include <Wire.h>
#include <Time.h>
#include <TimeAlarms.h>

I am working on Arduino 1.0, Windows 7. My aim is to build an intervallometer. It works fine but I do some calculations based on the time from Arduino was started (millis()). The use of Alarm.timerRepeat appears usefull for me. It compiles well alone, but when I try to use this function into my original project, it has no effects: project compiles, but my function is never call.
I was wondering if some libraries were using same ressources (same timer ?).

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: kmcnasty on Jan 03, 2012, 05:20 am
Hey all just wanting to know if it is possible to parse variable via the functions specified in the setting of alarms.

I have included an example below as i am unsure how to explain it. Not going to be my arduino for a few days and really really want to know if it will work for when i am :D.

Thanking you in advanced.



Code: [Select]

#include <Time.h>
#include <TimeAlarms.h>

void setup()
{

int length = 1000;

  Serial.begin(9600);
  setTime(8,29,0,1,1,11); // set time to Saturday 8:29:00am Jan 1 2011
 
  // create alarm
  Alarm.alarmRepeat(8,30,0, MorningAlarm(length));




}

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

void MorningAlarm(int slen){
  Serial.println("Alarm sounding.");   
  Alarm.delay(slen);
}


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

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Jan 03, 2012, 01:22 pm
Quote
Hey all just wanting to know if it is possible to parse variable via the functions specified in the setting of alarms.

If, as it appears, you are asking if you can use a variable to hold the value passed to the functions, then the answer is yes, of course you can.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: no245 on Jan 03, 2012, 05:25 pm
Is there a git repository for the Time library?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: ninja2 on Jan 17, 2012, 03:02 am
not sure about github, but the time library download can be found here:
http://arduino.cc/playground/Code/Time (http://arduino.cc/playground/Code/Time)

(not sure why is it in this unusal location, and not with the other libraries ?!?)
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mrTee on Jan 25, 2012, 10:54 pm
First of all, thanks for writing this very usefull library!  And of course, a request :-) I would like to use a syncTime function similar to setTime but registering the update as a sync. I do not want to use the setSyncProvider, I cannot instantaneously give back a sync time upon request. I see an commented out function header setExternalTime

The background is that I'm rewriting the DCF77 clock routine created by Mathias Dalheimer.  It translates a bit chain coming from a radio beacon every minute (in optimal conditions)  and ideally I would update the time immediately afterwards , rather than having to wait for Time callback. Could this be added to the lib?
Title: Will this work for 6 months?
Post by: schrockstudio on Feb 02, 2012, 07:21 pm
Hi I'm working on a relatively simple project where I want to time some LEDs to go on and off at slow intervals.
-throughout a one day period,
-then once a week have a different set of "alarms" to trigger the LEDs,
-then return to the usual pattern,
-then once a month have a different set of "alarms" to trigger the LEDs,
-then return to the usual pattern.

I've already tested and assembled the test hardware for the events, now all I need to do if figure out the code.

Someone mentioned
Quote
One thing to watch out for is that the Arduino clock isn't very precise so it will gain or lose time over long intervals (minutes per day, possibly a day or two over six months).


Is that problem solved with the "TimeAlarms Library?

Also when attempting to use time alarms I'm getting some error messages when just attempting to verify the example sketch.
Quote
/Applications/Arduino.app/Contents/Resources/Java/libraries/TimeAlarms/TimeAlarms.cpp:25:22: error: WProgram.h: No such file or directory
/Applications/Arduino.app/Contents/Resources/Java/libraries/TimeAlarms/TimeAlarms.cpp: In member function 'void TimeAlarmsClass::delay(long unsigned int)':
/Applications/Arduino.app/Contents/Resources/Java/libraries/TimeAlarms/TimeAlarms.cpp:256: error: 'millis' was not declared in this scope


Can someone shed a bit of light on my issues, queries? thanks!
-What are the error messages?
-Is TimeAlarms Library even what I should be using?
-Will I loose signifigant time accuracy over 6 months with TimeAlarms Library?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Feb 02, 2012, 07:36 pm
Quote
Is that problem solved with the "TimeAlarms Library?

If software could make your hardware operate better, don't you suppose that that software would be part of the core software?

Quote
Also when attempting to use time alarms I'm getting some error messages when just attempting to verify the example sketch.

And you've searched and found that the library has not been updated for Arduino 1.0, right? WPrograms.h was renamed to Arduino.h.

Quote
-Will I loose signifigant time accuracy over 6 months with TimeAlarms Library?

Whether your system gains or looses time is not a library-related issue.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: ninja2 on Feb 02, 2012, 09:09 pm
The time inaccuracy is due to the Arduino hardware, the library itself will not fix that.

You can improve accuracy by adding a Real Time Clock (RTC) breakout such as the DS1307. I'm finding the inaccuracy of a DS1307 Real Time Clock is typically to loose around 5 to 8 second every day. It can be more or less than this but it gives you an idea. At 5 secs/day that would be about 15 minutes lost in six months. If this áccuracy is not good enough for your project, there are two possible solutions:

1) buy a more accurate RTC, such as the DS3231. See this thread http://arduino.cc/forum/index.php/topic,87846.0.html (http://arduino.cc/forum/index.php/topic,87846.0.html)

2) run the clock for a few days and work out how much it gains/looses per day, then write software to compensate.

Your compiling problem is because you are using an old version of the time library . In the release notes for Arduino 1.0  it explains "wprogram.h" is now replaced by "arduino.h". You need to change the code to fix this. But it's your lucky day, to save you time I've attached a revised version of the Time library which has this update in Time.cpp:

#if ARDUINO >= 100
#include <Arduino.h>
#else
#include <WProgram.h>
#endif
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: schrockstudio on Feb 02, 2012, 10:20 pm
Thanks ninja!

upon reading more it seems that you cannot use millisecond delays with the timealarm lib.
At 9pm every sunday I want to set the array to do a simple choreographed sweep through the LEDs back and forth 60 times and that requires the LEDs to High/Low with 100 milliseconds delays.
-Is that not possible using TimeAlarm Lib?
-If I simply calculate Milliseconds 604,800,000(once a week) and use the Arduino's clock, what is the typical drift? I can live with a little change. if that change is consistant. ie, it looses/gains 26.44 seconds a day. I can plan my events accordingly to that.

The 6months/deadline starts in 4 days. so I cannot order any of those shields.

Also a concern I have is, what if there is a power surge? does the Arduino reset the program completely or start where it left off?

Thanks! Thanks thanks!!!



*edit. PaulS I just read your post, thanks for letting me know about the Lib update!
-So as it sounds the hardware timing inconsistency isn't solved by software/code. so that means it is an A)inconsistant time change?
or
B)just inconsistant between different Arduinos, so I could calculate my specific hardwares drift and adjust?

Thank you for helping!
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: bsbrum on Feb 12, 2012, 08:31 pm
Just a passing suggestion.

It seems like what you're describing is a set of modes. One mode for a period of time, and then another, and so on.

One thing you could do is use the Arduino's EEPROM (non-volatile RAM) to write the current mode, so that on power-cycle it can restart in the last mode, where it left off. You could likewise do something like tick off the number of hours in that mode, so your recovery to the last mode could also be a little more granular than just a restart from the beginning.

EEPROM tips here: http://arduino.cc/it/Tutorial/EEPROMWrite
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: phantom89 on Feb 18, 2012, 09:50 am
hi,
I need to include a clock in my project, that syncs with NTP. But im using an enc28j60 based ethernet controller(Using Ethercard library). so how can i modify the TimeNTP example to use it with my Ethernet controller.
(I have already established the internet connection)
Title: davidhbrown-RealTimeClockDS1307-ef34215 library
Post by: miker on Feb 24, 2012, 05:29 pm
I've downloaded and installed the subject library. The sketch (RealTimeClockDS1307_Test)
complies and loads without error but when I run it and view the Serial Monitor I just get
a sequence hex chars that do not appear to be incrementing... the output on
the Serial Monitor looks like this:

Code: [Select]

1: FF-1F-3F 1F:7F:7FP
2: FF-1F-3F 1F:7F:7FP
3: FF-1F-3F 1F:7F:7FP
4: FF-1F-3F 1F:7F:7FP
5: FF-1F-3F 1F:7F:7FP
6: FF-1F-3F 1F:7F:7FP
7: FF-1F-3F 1F:7F:7FP
8: FF-1F-3F 1F:7F:7FP
9: FF-1F-3F 1F:7F:7FP
10: FF-1F-3F 1F:7F:7FP
11: FF-1F-3F 1F:7F:7FP
12: FF-1F-3F 1F:7F:7FP
13: FF-1F-3F 1F:7F:7FP
14: FF-1F-3F 1F:7F:7FP
15: FF-1F-3F 1F:7F:7FP
16: FF-1F-3F 1F:7F:7FP
17: FF-1F-3F 1F:7F:7FP
18: FF-1F-3F 1F:7F:7FP
19: FF-1F-3F 1F:7F:7FP
20: FF-1F-3F 1F:7F:7FP
21: FF-1F-3F 1F:7F:7FP
22: FF-1F-3F 1F:7F:7FP
23: FF-1F-3F 1F:7F:7FP
24: FF-1F-3F 1F:7F:7FP
25: FF-1F-3F 1F:7F:7FP
Send ? for a list of commands.
26: FF-1F-3F 1F:7F:7FP
27: FF-1F-3F 1F:7F:7FP
28: FF-1F-3F 1F:7F:7FP


Looking at the DS1307 datasheet the default/power on  date/time should be  01/01/00 00:00:00 but I can't
get to this from FF-1F-3F 1F:7F:7FP ??
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: ninja2 on Feb 24, 2012, 09:48 pm
I don't know about that ''davidhbrown'' library but why not just use the stanndard time library of the examples provided in the arduino IDE ? (file>examples>time) That all works fine.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: dwitt on Feb 27, 2012, 01:38 am
I am looking at using this library for an internet connected timing device.  I noticed that now() uses millis() and prevMillis to update sysTime.  It would seem to me that millis() will wrap around or overflow after about 49.7 days.  Question: Should we not check if millis() is less than prevMillis and make the appropriate adjustment as this condition would be true if millis() overflowed?  I haven't worked out the code yet but does this make sense to anyone else?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Feb 27, 2012, 01:37 pm
Quote
Question: Should we not check if millis() is less than prevMillis and make the appropriate adjustment as this condition would be true if millis() overflowed?  I haven't worked out the code yet but does this make sense to anyone else?

There is no need. If millis() does overflow, and reset to a small value, millis() - prevMillis will still return the correct value (as long as that duration is less than 49.7 days).
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: dwitt on Mar 01, 2012, 03:38 am
Thanks.  This took me a while to figure out but then I realized it was unsigned arithmetic so you will always get a positive number that is the deference between the two regardless of which is bigger.  Nice!
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: JustinBEverett on Apr 14, 2012, 01:08 am
Ok, so trying to use the Example sketch where time is synced by serial port to computer.

Manually sending the time message, or attempting to use the supplied Processing sketch both result in the Arduino being stuck "waiting for sync message".

If I understand the code correctly, when the Arduino receives a sync message it should print it out, right? Well, it only prints out the 'T' and goes back to waiting for sync. This leads me to believe the message is being truncated for some reason, or it is not reading it all.

For example this is what the serial monitor looks like right after sending a sync message note the "T":
Code: [Select]
0:00:09 1 1 1970
0:00:10 1 1 1970
0:00:11 1 1 1970
0:00:12 1 1 1970
Twaiting for sync message
waiting for sync message
waiting for sync message
waiting for sync message


Can anyone else verify that these sketches work as intended with their own setup? If so, maybe point out what might be going wrong.

Thanks!

The code running on the arduino is simply the example sketch found in the Time library and on this page: http://arduino.cc/playground/Code/Time
Code: [Select]
#include <Time.h> 

#define TIME_MSG_LEN  11   // time sync to PC is HEADER followed by Unix time_t as ten ASCII digits
#define TIME_HEADER  'T'   // Header tag for serial time sync message
#define TIME_REQUEST  7    // ASCII bell character requests a time sync message

// T1262347200  //noon Jan 1 2010

void setup()  {
  Serial.begin(9600);
}

void loop(){   
  if(Serial.available() )
  {
    processSyncMessage();
  }
  if(timeStatus()!= timeNotSet)
    Serial.println("waiting for sync message");
  else     
      digitalClockDisplay(); 
  delay(1000);
}

void digitalClockDisplay(){
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print(" ");
  Serial.print(day());
  Serial.print(" ");
  Serial.print(month());
  Serial.print(" ");
  Serial.print(year());
  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);
}

void processSyncMessage() {
  // if time sync available from serial port, update time and return true
  while(Serial.available() >=  TIME_MSG_LEN ){  // time message consists of header & 10 ASCII digits
    char c = Serial.read() ;
    Serial.print(c); 
    if( c == TIME_HEADER ) {       
      time_t pctime = 0;
      for(int i=0; i < TIME_MSG_LEN -1; i++){   
        c = Serial.read();         
        if( c >= '0' && c <= '9'){   
          pctime = (10 * pctime) + (c - '0') ; // convert digits to a number   
        }
      }   
      setTime(pctime);   // Sync Arduino clock to the time received on the serial port
    } 
  }
}


The processing sketch I'm running is also the one included with the library.
Code: [Select]
/**
* SyncArduinoClock.
*
* portIndex must be set to the port connected to the Arduino
*
* The current time is sent in response to request message from Arduino
* or by clicking the display window
*
* The time message is 11 ASCII text characters; a header (the letter 'T')
* followed by the ten digit system time (unix time)
*/


import processing.serial.*;

public static final short portIndex = 1;  // select the com port, 0 is the first port
public static final char TIME_HEADER = 'T'; //header byte for arduino serial time message
public static final char TIME_REQUEST = 7;  // ASCII bell character
public static final char LF = 10;     // ASCII linefeed
public static final char CR = 13;     // ASCII linefeed
Serial myPort;     // Create object from Serial class

void setup() { 
  size(200, 200);
  println(Serial.list());
  println(" Connecting to -> " + Serial.list()[portIndex]);
  myPort = new Serial(this,Serial.list()[portIndex], 9600);
}

void draw()
{
  if ( myPort.available() > 0) {  // If data is available,
    char val = char(myPort.read());         // read it and store it in val
    if(val == TIME_REQUEST){
       long t = getTimeNow();
       sendTimeMessage(TIME_HEADER, t);   
    }
    else
    {
       if(val == LF)
           ; //igonore
       else if(val == CR)           
         println();
       else 
         print(val); // echo everying but time request
    }
  } 
}

void mousePressed() { 
  sendTimeMessage( TIME_HEADER, getTimeNow());   
}


void sendTimeMessage(char header, long time) { 
  String timeStr = String.valueOf(time); 
  myPort.write(header);  // send header and time to arduino
  myPort.write(timeStr);   
}

long getTimeNow(){
  // java time is in ms, we want secs   
  GregorianCalendar cal = new GregorianCalendar();
  cal.setTime(new Date());
  int tzo = cal.get(Calendar.ZONE_OFFSET);
  int dst = cal.get(Calendar.DST_OFFSET);
  long now = (cal.getTimeInMillis() / 1000) ;
  now = now + (tzo/1000) + (dst/1000);
  return now;
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: JustinBEverett on Apr 14, 2012, 11:56 am
I found the problem, the code on the website has a != where it should be a ==

The line:
Code: [Select]
if(timeStatus()!= timeNotSet)

Should read:
Code: [Select]
if(timeStatus() == timeNotSet)

Of course, reading it now, this makes way more sense.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: inkspell4 on Apr 17, 2012, 11:20 pm
I was wondering how to compensate for the lag as the display seems to always be a few seconds off but otherwise this seems to be a great work and library.
I'm trying to make a project that would display the message bellow as such on a LED Matrix and need the time to display as accurate as possible any help with the small lag would be helpful
My Name 5:18:05 Thursday April 17, 2012

or such
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Apr 18, 2012, 01:28 am
Quote
and need the time to display as accurate as possible

The lag is likely in your matrix code. Make that faster, or compensate by setting the time a few seconds ahead.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: inkspell4 on Apr 18, 2012, 06:01 pm
here is my code if you don't mind taking a look
were using an arduino uno with one of these parts
http://www.adafruit.com/products/555
Code: [Select]
#include <Time.h>

#include "HT1632.h"

#define DATA 2
#define WR 3
#define CS 4
#define CS2 5
#define TIME_MSG_LEN  11   // time sync to PC is HEADER followed by unix time_t as ten ascii digits
#define TIME_HEADER  'T'   // Header tag for serial time sync message
// use this line for single matrix
HT1632LEDMatrix matrix = HT1632LEDMatrix(DATA, WR, CS);

void setup() {
  Serial.begin(9600);
  matrix.begin(HT1632_COMMON_16NMOS);
  matrix.fillScreen();
  delay(500);
  matrix.clearScreen();
  matrix.setTextSize(1); // size 1 == 8 pixels high
  matrix.setTextColor(1); // 'lit' LEDs
}

void loop() {
  if(Serial.available() )
  {
    processSyncMessage();
  }
  if(timeStatus()!= timeNotSet)
  { 
    scroll("Name");
  }
  delay(500);
}
void scroll(String m)
{
  String i = "   " + m + "    ";
  for(int r = 0; r<i.length() + 27 *5; r++)
  {
    String q = i + digitalClockDisplay();
    matrix.setCursor((-r),0);
    matrix.print(q);
    matrix.writeScreen();
    delay(500);
    matrix.clearScreen();
  }
}
String digitalClockDisplay(){
  // digital clock display of the time
  String a = " ";
  a = a + hour();
  a = a + ":";
  a = a + minute();
  a = a + ":";
  a = a + second();
  a = a +(" ");
  a = a + (dayStr(weekday()));
  a = a +(" ");
  a = a + (day());
  a = a + (" ");
  a = a + (monthShortStr(month()));
  a = a + (" ");
  a = a + (year());
  Serial.println(a);
  return a;
}

String printDigits(int digits){
  String a = "";
  if(digits < 10)
  {
    a = "0" + digits;
  }
  else
  {
    a = "" + digits;
  }
  return a; 
}

void processSyncMessage() {
  // if time sync available from serial port, update time and return true
  while(Serial.available() >=  TIME_MSG_LEN ){  // time message consists of a header and ten ascii digits
    char c = Serial.read() ;
    Serial.print(c); 
    if( c == TIME_HEADER ) {       
      time_t pctime = 0;
      for(int i=0; i < TIME_MSG_LEN -1; i++){   
        c = Serial.read();         
        if( c >= '0' && c <= '9'){   
          pctime = (10 * pctime) + (c - '0') ; // convert digits to a number   
        }
      }   
      setTime(pctime);   // Sync Arduino clock to the time received on the serial port
    } 
  }
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Apr 18, 2012, 07:58 pm
Quote
here is my code if you don't mind taking a look

I looked. It's a wonder the code works at all. digitalClockDisplay makes extensive calls to the String constructor and copy constructor, wasting resources all over the place, to create what should be a fixed length string.

A global char array and a single call to sprintf() to populate it would be faster, and waste no memory AND result in a smaller sketch. Presuming, of course, that you get rid of the String in scroll, too.

Other than the delays caused by Serial.print() the time every 1/2 second, at just 9600 baud, I don't see any particular reason why the time on the matrix would be significantly behind.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: inkspell4 on Apr 18, 2012, 11:25 pm
Would you mind pointing out the corrections that need to be made to help it run faster and cleaner it would be very helpful
Thanks
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mrTee on Apr 19, 2012, 11:45 am
I hope I'm not stepping over the line of crossposting, here, thanks for the Time library, I used it in my DCF77 library and significantly cleaned up the code. Also, I made it to work well with the setSyncProvider callback:

I opened a thread about it here (http://arduino.cc/forum/index.php/topic,102039.msg765424.html).

Please let me know if you have suggestions for improvements!

Thijs
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: ninja2 on Apr 19, 2012, 10:19 pm

Would you mind pointing out the corrections that need to be made to help it run faster and cleaner ...


have a read through this thread where problems with String are discussed, and PaulS even provided an example of how to use sprintf() that may help you. it worked for me!

and here's a full explanation of sprintf() works:
http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/ (http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/)
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mrgoodcat on Apr 22, 2012, 04:22 pm
Hi folks! I´m building a Garduino system!

every time i try to verify the code, the arduino says:


`error compiling!`

" C:\Users\9k\Desktop\arduino-1.0\libraries\DateTime\DateTime.cpp:15:20: error: wiring.h: No such file or directory
C:\Users\9k\Desktop\arduino-1.0\libraries\DateTime\DateTime.cpp: In member function 'void DateTimeClass::setTime(time_t)':
C:\Users\9k\Desktop\arduino-1.0\libraries\DateTime\DateTime.cpp:28: error: 'millis' was not declared in this scope
C:\Users\9k\Desktop\arduino-1.0\libraries\DateTime\DateTime.cpp: In member function 'time_t DateTimeClass::now()':
C:\Users\9k\Desktop\arduino-1.0\libraries\DateTime\DateTime.cpp:43: error: 'millis' was not declared in this scope
e "



here is the code i use:





#include <DateTime.h>

//define analog inputs to which we have connected our sensors
int moistureSensor = 0;
int lightSensor = 1;
int tempSensor = 2;

//define digital outputs to which we have connecte our relays (water and light) and LED (temperature)
int waterPump = 7;
int lightSwitch = 8;
int tempLed = 2;

//define variables to store moisture, light, and temperature values
int moisture_val;
int light_val;
int temp_val;

//decide how many hours of light your plants should get daily
float hours_light_daily_desired = 14;

//calculate desired hours of light total and supplemental daily based on above values
float proportion_to_light = hours_light_daily_desired / 24;
float seconds_light = 0;
float proportion_lit;

//setup a variable to store seconds since arduino switched on
float start_time;
float seconds_elapsed;
float seconds_elapsed_total;
float seconds_for_this_cycle;

void setup() {
//open serial port
Serial.begin(9600);
//set the water, light, and temperature pins as outputs that are turned off
pinMode (waterPump, OUTPUT);
pinMode (lightSwitch, OUTPUT);
pinMode (tempLed, OUTPUT);
digitalWrite (waterPump, LOW);
digitalWrite (lightSwitch, LOW);
digitalWrite (tempLed, LOW);

//establish start time
start_time = DateTime.now();
seconds_elapsed_total = 0;

}
void loop() {
// read the value from the moisture-sensing probes, print it to screen, and wait a second
moisture_val = analogRead(moistureSensor);
Serial.print("moisture sensor reads ");
Serial.println( moisture_val );
delay(1000);
// read the value from the photosensor, print it to screen, and wait a second
light_val = analogRead(lightSensor);
Serial.print("light sensor reads ");
Serial.println( light_val );
delay(1000);
// read the value from the temperature sensor, print it to screen, and wait a second
temp_val = analogRead(tempSensor);
Serial.print("temp sensor reads ");
Serial.println( temp_val );
delay(1000);
Serial.print("seconds total = ");
Serial.println( seconds_elapsed_total );
delay(1000);
Serial.print("seconds lit = ");
Serial.println( seconds_light);
delay(1000);
Serial.print("proportion desired = ");
Serial.println( proportion_to_light);
delay(1000);
Serial.print("proportion achieved = ");
Serial.println( proportion_lit);
delay(1000);

//turn water on when soil is dry, and delay until soil is wet
if (moisture_val < 850)
{
digitalWrite(waterPump, HIGH);
}

while (moisture_val < 850)
{
delay(10000);
moisture_val = analogRead(moistureSensor);
}

digitalWrite(waterPump, LOW);

//update time, and increment seconds_light if the lights are on
seconds_for_this_cycle = DateTime.now() - seconds_elapsed_total;
seconds_elapsed_total = DateTime.now() - start_time;
if (light_val > 900)
{
seconds_light = seconds_light + seconds_for_this_cycle;
}

//cloudy days that get sunny again: turn lights back off if light_val exceeds 900. this works b/c the supplemental lights aren't as bright as the sun:)
if (light_val > 900)
{
digitalWrite (lightSwitch, LOW);
}

//turn off lights if proportion_lit>proportion_to_light, and then wait 5 minutes
if (proportion_lit > proportion_to_light)
{
digitalWrite (lightSwitch, LOW);
delay (300000);
}

//figure out what proportion of time lights have been on
proportion_lit = seconds_light/seconds_elapsed_total;

//turn lights on if light_val is less than 900 and plants have light for less than desired proportion of time, then wait 10 seconds
if (light_val < 900 and proportion_lit < proportion_to_light)
{
digitalWrite(lightSwitch, HIGH);
delay(10000);
}

//turn on temp alarm light if temp_val is less than 850 (approximately 50 degrees Fahrenheit)
if (temp_val < 850)
{
digitalWrite(tempLed, HIGH);
}

}


Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Apr 22, 2012, 05:17 pm
Is there some part of:
Quote
error: wiring.h: No such file or directory

that is confusing, misleading, or does not apply to you?

Have you made any attempt to search for this error message on the forum? The wiring.h file was renamed to wiring_private.h. This means that code should NOT have been directly including that file. The correct file to have included was WProgram.h, which was renamed to Arduino.h.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: maartend on May 06, 2012, 11:16 am
I'm trying to use this library but I get into some problems. I have the TimeNTP example and try to compile it. After setting the packet sizes I get these errors while compiling:
Code: [Select]
In file included from TimeNTP.cpp:10:
/home/maarten/arduino-1.0/libraries/Ethernet/UdpBytewise.h:70: error: conflicting return type specified for ?virtual void UdpBytewiseClass::write(uint8_t)?
/home/maarten/arduino-1.0/hardware/arduino/cores/arduino/Print.h:48: error:   overriding ?virtual size_t Print::write(uint8_t)?


When I fix that by changing virtual void UdpBytewiseClass::write(uint8_t) to virtual size_t UdpBytewiseClass::write(uint8_t), the error is
Code: [Select]
In file included from /home/maarten/arduino-1.0/libraries/Ethernet/EthernetClient.cpp:1:
/home/maarten/arduino-1.0/libraries/Ethernet/utility/w5100.h:14:17: error: SPI.h: No such file or directory

I certainly have SPI.h.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on May 06, 2012, 03:59 pm
My copy of Arduino 1.0 does not have a file called UdpBytewise.h or UdpBytewise.cpp in the Ethernet folder in the libraries directory. I'm wondering why yours does. Have you been adding files to the libraries/Ethernet folder?

If so, you need to delete the entire Arduino 1.0 folder and reinstall.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: maartend on May 06, 2012, 08:07 pm
On http://arduino.cc/playground/Code/Time it says
Quote
To use all of the features in the library, you'll need the UDPbitewise library, found here (https://bitbucket.org/bjoern/arduino_osc/get/tip.zip).


So that's why I have them.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: katzmatt on May 13, 2012, 04:00 am
hey im having some issues with the processing side of the library, on a fresh install of this code it will give an error saying array index out of bounds exception 1
on line 47 

it says at SyncArduinoClock.setup(SyncArduinoClock.java:47)
at processing.core.PAplet.handledraw(Unknown Source)
at processing.core.PApplet.run(Unknown Source)
at java.lang.Thread.run(thread.java:662)

and in the code window it highlights

println(" Connecting to -> " + Serial.list()[portIndex]);

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on May 13, 2012, 04:34 pm
Code: [Select]
Serial.list()[portIndex]
is an array access. If the array index, portIndex, is less than 0 or greater than or equal the length of the list, which could be 0, then, there is an array index out of bounds problem.

We can't tell from what you posted how long the list is that the Serial.list() method returns, or what the value in portIndex is. You will need to make sure that the value in portIndex is legal.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: katzmatt on May 14, 2012, 08:49 pm
the exact code i am running is the processing sketch from the time library and my port index is 3 because the arduino is on port 3
but even if i made no modifications to this code it still gives me an error
is there a way to just tell it what port number and do away with the serial list because i know the port and this is unnecissary
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on May 14, 2012, 08:54 pm
Quote
my port index is 3 because the arduino is on port 3

The portIndex value and the COM port number bear no relationship to each other.

Add 3 statements to the Processing sketch, before the println(" Connecting to -> " + Serial.list()[portIndex]); statement:
Code: [Select]
println("Serial ports");
println("=================");
println(Serial.list());
println("=================");

The list of serial ports that Processing knows about will be between the two rows of equal signs. Show us the output.

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: karles on May 15, 2012, 04:22 pm
Arduino 1 can not play TimeSerial.pde

I tested TimeSerial.pde after install Time llibrary in /home/carles/ARDUINO/arduino-1.0/libraries/Time but Arduino show me this error:

TimeSerial.cpp:12:20: error: Time.h: El fitxer o directori no existeix (File not found)
TimeSerial.cpp:24: erreur: 'time_t' does not name a type
TimeSerial.cpp: In function 'void setup()':
TimeSerial.cpp:27: erreur: 'requestSync' was not declared in this scope
TimeSerial.cpp:27: erreur: 'setSyncProvider' was not declared in this scope
TimeSerial.cpp: In function 'void loop()':
TimeSerial.cpp:36: erreur: 'timeStatus' was not declared in this scope
TimeSerial.cpp:36: erreur: 'timeNotSet' was not declared in this scope
TimeSerial.cpp:38: erreur: 'timeSet' was not declared in this scope
TimeSerial.cpp: In function 'void digitalClockDisplay()':
TimeSerial.cpp:46: erreur: 'hour' was not declared in this scope
TimeSerial.cpp:47: erreur: 'minute' was not declared in this scope
TimeSerial.cpp:48: erreur: 'second' was not declared in this scope
TimeSerial.cpp:50: erreur: 'day' was not declared in this scope
TimeSerial.cpp:52: erreur: 'month' was not declared in this scope
TimeSerial.cpp:54: erreur: 'year' was not declared in this scope
TimeSerial.cpp: In function 'void processSyncMessage()':
TimeSerial.cpp:72: erreur: 'time_t' was not declared in this scope
TimeSerial.cpp:72: erreur: expected `;' before 'pctime'
TimeSerial.cpp:76: erreur: 'pctime' was not declared in this scope
TimeSerial.cpp:79: erreur: 'pctime' was not declared in this scope
TimeSerial.cpp:79: erreur: 'setTime' was not declared in this scope
TimeSerial.cpp: At global scope:
TimeSerial.cpp:84: erreur: 'time_t' does not name a type

Can somebody  help me ?
Thanks.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on May 15, 2012, 05:24 pm
Quote
I tested TimeSerial.pde after install Time llibrary in /home/carles/ARDUINO/arduino-1.0/libraries/Time

That was the wrong place. The Time library is not a core library.

Did you restart the IDE afterwards?

Code: [Select]
TimeSerial.cpp:12:20: error: Time.h: El fitxer o directori no existeix (File not found)
This means that either you didn't restart the IDE or you didn't install the library correctly.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: WaterPoloTank on May 19, 2012, 12:20 am
I am running the example code from the Time library page here: http://www.arduino.cc/playground/Code/Time
I am sure that it is a stupid rookie mistake but I can't get it to work right. The code itself is this:
#include <Time.h> 

#define TIME_MSG_LEN  11   // time sync to PC is HEADER followed by Unix time_t as ten ASCII digits
#define TIME_HEADER  'T'   // Header tag for serial time sync message
#define TIME_REQUEST  7    // ASCII bell character requests a time sync message

// T1262347200  //noon Jan 1 2010

void setup()  {
  Serial.begin(9600);
}

void loop(){   
  if(Serial.available() )
  {
    processSyncMessage();
  }
  if(timeStatus()!= timeNotSet)
    Serial.println("waiting for sync message");
  else     
      digitalClockDisplay(); 
  delay(1000);
}

void digitalClockDisplay(){
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print(" ");
  Serial.print(day());
  Serial.print(" ");
  Serial.print(month());
  Serial.print(" ");
  Serial.print(year());
  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);
}

void processSyncMessage() {
  // if time sync available from serial port, update time and return true
  while(Serial.available() >=  TIME_MSG_LEN ){  // time message consists of header & 10 ASCII digits
    char c = Serial.read() ;
    Serial.print(c); 
    if( c == TIME_HEADER ) {       
      time_t pctime = 0;
      for(int i=0; i < TIME_MSG_LEN -1; i++){   
        c = Serial.read();         
        if( c >= '0' && c <= '9'){   
          pctime = (10 * pctime) + (c - '0') ; // convert digits to a number   
        }
      }   
      setTime(pctime);   // Sync Arduino clock to the time received on the serial port
    } 
  }
}

And the serial monitor output is this:

0:00:00 0 0 1970
0:00:01 1 1 1970
0:00:02 1 1 1970
0:00:03 1 1 1970
0:00:04 1 1 1970
0:00:05 1 1 1970
0:00:06 1 1 1970
0:00:07 1 1 1970
0:00:08 1 1 1970
0:00:09 1 1 1970
0:00:10 1 1 1970
0:00:11 1 1 1970
So how do I get to the right time?

I have read through maybe 4 forums and didn't see the answer. Like I said, I am a rookie and I'm sure its a silly, stupid mistake but what do I do to get the right time? Please help.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on May 19, 2012, 02:59 am
The output from the PC should look like "T1262347200". The numeric portion will change. The leading T will not.

The output that you show is the (incorrect) date and time, suggesting that there is no communication happening between the Arduino and the PC.

You did start the Processing application that runs on the PC, didn't you?

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: WaterPoloTank on May 20, 2012, 02:48 am
I did not start any Processing application on the PC. I just downloaded both the libraries and the example code, uploaded the code to our Mega. Is that not right? I'm sorry for being so ignorant on this subject, I tried reading up, this library just isn't clicking with me. Sorry again and thanks for the help.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: odometer on May 20, 2012, 06:08 am
Forget about any Processing application. In order to run it, you will have to download some 200-megabyte piece of software... just forget it. Instead, use my method:

1) Curse the author of the library.
2) Go to http://unixtime.info/ (http://unixtime.info/) and look at the 10-digit number shown near the top right hand corner of the page.
3) Repeat step #1 as you adjust this number for your time zone. You will have to do some mental arithmetic.

US time zones:
Pacific Daylight Time: subtract 25200
Mountain Daylight Time: subtract 21600
Central Daylight Time: subtract 18000
Eastern Daylight Time: subtract 14400

European time zones:
Western European Summer Time: add 3600
Central European Summer Time: add 7200
Eastern European Summer Time: add 10800

4) Now, take that example code you got from the Time library page, and run it.
5) Now since the number on the unixtime.info page has changed, you will have to repeat step #3. Also repeat step #1.
6) Using the Serial Monitor feature of the Arduino software, type in something like "T1000000000". The T has to be capital, and in place of 1000000000, use the result of Step #5.
7) Send that command (the T with the 10-digit number) to the Arduino.

Note: When Daylight Saving Time / Summer Time ends, you will have to repeat the above, but with a different number to subtract / add for the time zone.

US time zones:
Pacific Standard Time: subtract 28800
Mountain Standard Time: subtract 25200
Central Standard Time: subtract 21600
Eastern Standard Time: subtract 18000

European time zones:
Western European (Standard) Time: don't add or subtract anything
Central European (Standard) Time: add 3600
Eastern European (Standard) Time: add 7200
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on May 20, 2012, 03:00 pm
Quote
I just downloaded both the libraries and the example code, uploaded the code to our Mega.

Some of the code was for the Arduino. Some was a Processing application. It is the Processing application that responds to the request for the time. If you are not running the application that is supposed to supply the time information, expecting a response is not a realistic expectation.

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on May 20, 2012, 03:01 pm
Quote
1) Curse the author of the library.

How about we all curse you for choosing a different method of getting the time, that does not expand well to other data that the PC has that might be interesting to the Arduino?

Idiot.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: odometer on May 21, 2012, 12:18 am

Quote
1) Curse the author of the library.

How about we all curse you for choosing a different method of getting the time, that does not expand well to other data that the PC has that might be interesting to the Arduino?

Idiot.


If you just want to set the time, my method is perhaps the most straightforward for doing so.
Or now that you mention it, maybe not.

All right. Here's another method for computing the 10-digit number for setting the time:
This is all client-side, no internet access needed.
Open a spreadsheet program.
In cell A1 goes: =NOW()
In cell A2 goes: 1970-01-01 00:00
In cell A3 goes: =(A1-A2)*86400
Now, look at the number in A3. The part before the decimal point is the number you need.
To update the time, just recalculate the data.

As for "other data the PC has that might be interesting to the Arduino": in what form is this data stored? How you communicate this data to the Arduino, as well as how you have the Arduino handle the data once received, depends very heavily on the format in which you have the data.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: odometer on May 21, 2012, 12:23 am
You might also want to see the code I have posted here:
http://arduino.cc/forum/index.php/topic,101401.0.html (http://arduino.cc/forum/index.php/topic,101401.0.html)
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: WaterPoloTank on May 21, 2012, 10:42 pm
Thank you very much for the help. Our group could not figure out this Time library and we discovered that we there were better libraries for our purposes. I.e. we need to run a function every five minutes. We originally thought we needed to use a date and time system but have recently discovered the timer library. Thank you again for your help, it is greatly appreciated.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: robtillaart on May 23, 2012, 05:40 pm

In the category suggestions

this thread provides an interesting proposol to correct internal timing, think it is food for thought for the Time lib

- http://arduino.cc/forum/index.php/topic,106517.0.html -

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: odometer on May 27, 2012, 03:07 am
I have an idea for accurately tracking fractional seconds, here:
http://arduino.cc/forum/index.php/topic,107254.0.html (http://arduino.cc/forum/index.php/topic,107254.0.html)

I believe that my idea will run rather efficiently, but the main advantage is that it handles slight inaccuracies of the oscillator in a very natural (for a microprocessor) way.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: sumustinis on Jun 02, 2012, 01:08 pm
Hi there,
Does anyone has a problem like I`m having with Time library? As soon as I do #include <Time.h> and try to verify in any sketch the Arduino IDE throws out compilation error below

/usr/share/arduino/libraries/Time/DateStrings.cpp:18:18: error: variable 'monthStr1' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: jan_bl on Jul 11, 2012, 06:51 pm
I got the same errors here with arduino 18, 22 and 1.01. and different Time lib versions.

/usr/share/arduino/libraries/Time/DateStrings.cpp:18:18: error: variable 'monthStr1' must be const in order to be put into read-only section by means of '__attribute__((progmem))'

The fix for my debian system was:

go back to gcc-avr version 4.3.5-1 * and
go back to avr-libc version 1.6.8-2 *

Now everything compiles just fine

* i updated to gcc-avr 4.7.0-2 and avr-libc 1.8.0-2 which broke compiling TIME libs.

Having fun again
Jan
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Roger_at_CCCC on Jul 22, 2012, 04:54 am
Hello, I'm trying to find out why the Examples in the Time library won't compile. 

I recently downloaded Ardiuno 1.0.1, then followed the directions on the Arduino playground - Time libary page at:  http://arduino.cc/playground/Code/Time

First, I downloaded the time.zip file, then extracted the folders within it.  This yielded one folder named "Time" as well as three folders within this top level "Time" folder.  These three folders were named "DS1307RTC", "Time", and "TimeAlarms" . 

Then I copied the "Time" library into the Arduino "libraries" folder, then started Arduino.exe, and selected TimeSerial.pde from the Examples list.  This sketch loaded and I pressed "Verify" and received the error message : "The 'BYTE' keyword is no longer supported.  "  All of the example sketches failed to compile but had different error messages. 

I think I did everything correct, and did it both for the top level "Time" folder and also for the "Time" folder contained within the top level folder.  Neither one worked. 

Unless I'm doing something wrong, there must be something wrong with the folder structure of the library, but, if so, I am surprised this error is not already well known. 

I'm not very experienced with Arduino, so that's why it is confusing. 

Thanks in advance for any information about this problem.   
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: lion032 on Jul 22, 2012, 01:04 pm
Hello everybody!

In my project I needed to set the ds1307rtc from individual input something that the ds1307 included with time lack.

So I want to shear the updated file that include now the function:

 
Code: [Select]
void set(int hour, int min, int sec, int day, int month, int year);

year input can be either in 4 or 2 digit format.

You can download it from my project's sourceforge page:

http://sourceforge.net/projects/computerizedtel/files/DS1307RTCNEW.rar/download

Enjoy
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Jul 22, 2012, 03:21 pm
Quote
Then I copied the "Time" library into the Arduino "libraries" folder, then started Arduino.exe, and selected TimeSerial.pde from the Examples list.  This sketch loaded and I pressed "Verify" and received the error message : "The 'BYTE' keyword is no longer supported.  "  All of the example sketches failed to compile but had different error messages. 

There are two libraries folders - one in your sketch folder and one in the folder where you installed the Arduino IDE. Which one did you copy the Time library to? The one in the Arduino IDE folder is NOT the proper place for user-downloaded libraries.

The BYTE message indicates that the library that contains it has not been updated for 1.0+.

How to update it has been covered many times, many ways, many places.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Roger_at_CCCC on Jul 22, 2012, 03:27 pm
Pauls:  Please indicate at least one or two of the places where update instructions are given.  I'm new to this and so don't know where to look.  Thanks !! 
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: dxw00d on Jul 22, 2012, 03:31 pm
http://arduino.cc/en/Main/ReleaseNotes
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Jul 22, 2012, 03:38 pm
Quote
I'm new to this and so don't know where to look.

There is a search field on every single page. You could type your exact error message into that field and see what comes up.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Quarencia on Aug 06, 2012, 07:59 pm
Is anyone maintaining the time and timealarms libraries?  If so, can a version updated to support 1.0.1 be made available?  I've searched and can't find it, so if this is already done, please direct me to the latest location.  I have modified the version accessible from on the playground page to work wtih 1.0.1 for my own use, but it would cause a lot less confusion if there were an updated version available.  If this were done, PAULS wouldn't have to tell quite so many people how to use the search function... :)
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: JChristensen on Aug 13, 2012, 12:57 pm

Is anyone maintaining the time and timealarms libraries?  If so, can a version updated to support 1.0.1 be made available?


Good question, I would hope so.

Quote

I've searched and can't find it, so if this is already done, please direct me to the latest location.  I have modified the version accessible from on the playground page to work wtih 1.0.1 for my own use, but it would cause a lot less confusion if there were an updated version available.


What mods did you make? The only change to the libraries that I found was necessary was that TimeAlarms.cpp needed the following. Strange because the Time and DS1307RTC libraries were updated for 1.0. Several of the examples have other version-related issues, though.

Code: [Select]
#if ARDUINO >= 100
#include <Arduino.h>
#else
#include <WProgram.h>
#endif


Quote

If this were done, PAULS wouldn't have to tell quite so many people how to use the search function... :)


Indeed ;)
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: StuC on Aug 15, 2012, 01:43 am
A couple of folks earlier in the thread were wondering why the TimeGPS example didn't seem to be doing anything - I was too, until I spent a little while looking at it this evening. I've written it up over on my blog (http://blog.cuyahoga.co.uk/2012/08/time-hes-waiting-in-the-wings/), but the basic problem is that the sketch invokes the sync provider function before any data has actually been received from the GPS, so there's never going to a suitable date/time at that point. However, because TinyGPS returns a value and the sketch doesn't validate it, it thinks that zero is a valid date value and that gets mapped to 31/12/1999. Job jobbed, date set, nothing more to do here then. Except that this means you don't see anything in the Serial Monitor window except "Waiting for GPS time ...".

I've added in some validation checks to the sketch and updated it to reference the SoftwareSerial libbrary instead of NewSoftSerial and it now works as expected. If anyone is maintaining the Time library and its examples, feel free to roll the code into the download version.

(http://farm9.staticflickr.com/8289/7784708402_241115b07d.jpg)

Cheers, Stu
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: charlya on Aug 26, 2012, 02:23 pm
I've been having problems using Time library with watchdog timer. What I see is that at seemingly random times the Arduino gets reset.

I now believe its down to the following code in Time.cpp:

time_t now(){
  while( millis() - prevMillis >= 1000){     
    sysTime++;
    prevMillis += 1000;   
#ifdef TIME_DRIFT_INFO
    sysUnsyncedTime++; // this can be compared to the synced time to measure long term drift     
#endif   
  }
  ...


in that if the clock drift is negative, the while loop can be quite expensive.
I've replaced it with:

time_t now(){
  unsigned long nowMillis = millis();
  unsigned long diffMillis = 0;
  if (nowMillis > prevMillis) diffMillis = nowMillis - prevMillis;
  else diffMillis = prevMillis - nowMillis;
  unsigned long diffSecs = diffMillis / 1000;
  if (0 != diffSecs)
  {
   if (nowMillis > prevMillis) {
     sysTime += diffSecs;
     prevMillis += diffMillis;
#ifdef TIME_DRIFT_INFO
     sysUnsyncedTime += diffSecs // this can be compared to the synced time to measure long term drift     
#endif   
   } else {
     sysTime -= diffSecs;
     prevMillis -= diffMillis;
#ifdef TIME_DRIFT_INFO
     sysUnsyncedTime -= diffSecs; // this can be compared to the synced time to measure long term drift     
#endif
   }
  }
  ...


is this library maintained? Do you agree with this is an issue and with the fix?
regards
Charly
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Mackhack on Sep 08, 2012, 06:14 am
Did you ever get to resolve the issue? I'm having the same issue and have no clue how to fix it  :~
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: pYro_65 on Sep 08, 2012, 08:43 am
Looks like 'charlya' had a go at fixing it. open up the library file ( Time.cpp ) and find the function 'now()', comment out the first 7 lines ( first code snippet ) and copy in the longer second code.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mrty on Sep 09, 2012, 02:21 am

Hello, I'm trying to find out why the Examples in the Time library won't compile. 

I recently downloaded Ardiuno 1.0.1, then followed the directions on the Arduino playground - Time libary page at:  http://arduino.cc/playground/Code/Time

First, I downloaded the time.zip file, then extracted the folders within it.  This yielded one folder named "Time" as well as three folders within this top level "Time" folder.  These three folders were named "DS1307RTC", "Time", and "TimeAlarms" . 

Then I copied the "Time" library into the Arduino "libraries" folder, then started Arduino.exe, and selected TimeSerial.pde from the Examples list.  This sketch loaded and I pressed "Verify" and received the error message : "The 'BYTE' keyword is no longer supported.  "  All of the example sketches failed to compile but had different error messages. 

I think I did everything correct, and did it both for the top level "Time" folder and also for the "Time" folder contained within the top level folder.  Neither one worked. 

Unless I'm doing something wrong, there must be something wrong with the folder structure of the library, but, if so, I am surprised this error is not already well known. 

I'm not very experienced with Arduino, so that's why it is confusing. 

Thanks in advance for any information about this problem.   



I don't know if this is the right way to do it, but I switched 'BYTE' with 'byte(0)' and now it works for me.

-Ty
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Docedison on Oct 06, 2012, 09:58 am
This is still an issue. I've some patched code that works 1/2 of the time.. I would sure like to see a Test sketch that works...
@Mem: Great Book, Was Extremely helpful... and I re-read it frequently Thank You Sir.


I took your GPS time sketch and married it to a GPS and a GLCD separately both work but:
This one fails to transfer data from the gps routines to the clock I am very tired... of looking at it, There are some debug things and the separators need to be fixed but
I have a gps unit working with a sketch I put together from harts suggestions and a graphics LCD but there were *several* compelling reasons to use your sketch so...
**MORE at Bottom**
Code: [Select]
/*
* TimeGPS_Round1.ino
* example code illustrating time synced from a GPS
*
*/

#include <Time.h>
#include <TinyGPS.h>
// GPS Library is the work of Mikal Hart
#include <UTFT.h>
extern uint8_t SmallFont[];
UTFT myGLCD(ITDB32S,38,39,40,41);   // Mega2560

TinyGPS gps;

const int offset = -7;   // offset hours from gps time (UTC)
time_t prevDisplay = 0; // when the digital clock was displayed

void setup()
{
 myGLCD.InitLCD();  // '0' is default landscape '1' is portrait
 myGLCD.setFont(SmallFont);
 //myGLCD.clrScr();

 //Serial1.begin(9600);  // 9600 baud for Skylabs SKM53
 Serial1.begin(4800);  // 4800 baud for U-Blox_6-1
 myGLCD.print("Waiting for GPS time ... ",8,0);
 setSyncProvider(gpsTimeSync);
 myGLCD.clrScr();
}

void loop()
{
 while (Serial1.available())
 {
   gps.encode(Serial1.read()); // process gps messages
   // Debug Messages
   myGLCD.print("Waiting for GPS time ... ",CENTER,120);  [color=red]// This works[/color]
   myGLCD.printNumI(hour(),64,24,2,'0'); // Prints 2 digit hour with leading 0
 //myGLCD.print(":",76 ,24); // separator not really rerquired
 myGLCD.printNumI(minute(),84,24,2,'0');
   myGLCD.printNumI(second(),104,24,2,'0');
  // End of Debug messages
 }
 if(timeStatus()!= timeNotSet)
 
 {
   if( now() != prevDisplay) //update the display only if the time has changed
   {
    myGLCD.print("Waiting for GPS time ... ",CENTER,110);  [color=orange]//This doesn't it never gets here[/color]  
     prevDisplay = now();
     digitalClockDisplay();  
   }
 }
}

void digitalClockDisplay(){
 // digital clock display of the time

 myGLCD.setColor(255,255,0);
 myGLCD.print("Date :",8 ,8);
 myGLCD.printNumI(month(),64,8,2,'0'); // Prints 2 digit month with leading 0
 myGLCD.print("/",80 ,8);  //
 myGLCD.printNumI(day(),88,8,2,'0');  // Prints 2 digit day with leading 0
 myGLCD.print("/20",104,8);
 myGLCD.printNumI(year(),112,8);
 myGLCD.print("Time :",8 ,24);
 myGLCD.printNumI(hour(),64,24,2,'0'); // Prints 2 digit hour with leading 0
 //myGLCD.print(":",76 ,24); // separator not really rerquired
 myGLCD.printNumI(minute(),84,24,2,'0');
 // myGLCD.print(":",94 ,24);
 myGLCD.printNumI(second(),104,24,2,'0');
}
/* NOT REQUIRED, UTFT LIB DOES THIS NICELY
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);
}
*/
time_t gpsTimeSync(){

 //  returns time if avail from gps, else returns 0
 unsigned long fix_age = 0 ;
 gps.get_datetime(NULL,NULL, &fix_age);
 //unsigned long time_since_last_fix;  // *****COMMENTING OUT THIS*****  [b]Yeah I know this is stupid... but when I did it I was too @ 4:00 AM <BG>[/b]
// if(fix_age < 1000)   //  *****AND THIS*****
   return gpsTimeToArduinoTime(); // return time only if updated recently by gps  
// return 0;  // *****FIXED THE ISSUE... Why is an issue??*****
}

time_t gpsTimeToArduinoTime()
{
 myGLCD.print("Waiting for GPS time ... ",CENTER,90);
 // returns time_t from gps date and time with the given offset hours
 tmElements_t tm;
 int year;
 gps.crack_datetime(&year, &tm.Month, &tm.Day, &tm.Hour, &tm.Minute, &tm.Second, NULL, NULL);
 tm.Year = year - 1970;
 time_t time = makeTime(tm);
 
 return time + (offset * SECS_PER_HOUR);
}


{Edit //****COMMENT**** Are the things I changed
Any Help would be appreciated I attached the file W/O the commented mods described above.
{Edit. I added the finished metrology functions to the basic timeGPS Sketch and used an Itead 3.2 GLCD because of the really nice libs that come with it.
UTFT  By Henning Karlsen works well with the Itead product... At about $17.00 a copy for a 3.2" 320X240 display it's hard to beat (W/Touch & SDcard)

Bob
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: nickgammon on Oct 15, 2012, 05:00 am
Code: [Select]

// return 0;  // *****FIXED THE ISSUE... Why is an issue??*****


I'm not sure what you are asking here.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Docedison on Oct 15, 2012, 05:53 am
Commenting both lines caused the GPS time to work... sort of it is on page 3 of this group second up from the last post. After I commented out the code It worked. It was @ 4AM for me... I didn't see that I had commented a comment.. and I then posted a request the next day and later asked you to follow up on it later. In the second attachment is the core of my measurement sketch, I'll post the full thing If it will help as I would like whatever criticism it deserves... and that I might deserve... I've thrown enough bricks to take a few...

Bob
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Docedison on Oct 15, 2012, 06:15 am
Here is Ver 1_2 of my little sketch for a Mega2560 It used a GPS receiver, a BMP085 Barometer/thermometer, a DHT22 hygrometer and a 320X240 Itead display.
Comments are Most welcome. It's attached to the previous post. and "Presented Here":
Code: [Select]

/*
* TimeGPS.pde
* example code illustrating time synced from a GPS
* Robert K.Johnson
*/
#include "DHT.h"
#include <Time.h>
#include <TinyGPS.h>
// GPS Library is the work of Mikal Hart
#include <UTFT.h>
#include <Wire.h>
#include <BMP085.h>
extern uint8_t SmallFont[];
UTFT myGLCD(ITDB32S,38,39,40,41);   // Mega2560
BMP085 dps = BMP085();      // Digital Pressure Sensor instance
TinyGPS gps; // GPS Receiver instance
#define DHTPIN 8     // what pin we're connected to
#define DHTTYPE DHT22   // DHT 22  (AM2302)
DHT dht(DHTPIN, DHTTYPE);

long Temperature = 0, Pressure = 0, Altitude = 0, Far = 0, Pres = 0; //, Far2 = 0;    // Variable's for display and conversion
const int offset = -7;   // offset hours from gps time (UTC)
time_t prevDisplay = 0; // when the digital clock was displayed "0"

void setup()
{
  Wire.begin();    // Start Wire (IIC)
  delay(1000);    // Waait for IIC to init.
  dht.begin();
  myGLCD.InitLCD();  // '0' is default landscape '1' is portrait
  myGLCD.setFont(SmallFont);
  //Serial1.begin(9600);  // 9600 baud for Skylabs SKM53
  Serial1.begin(4800);  // 4800 baud for U-Blox_6-1

  setSyncProvider(gpsTimeSync);
  myGLCD.clrScr();
  myGLCD.setColor( 180,0, 0);
  myGLCD.drawRect(0, 6, 150,90);
  // uncomment for different initialization settings
  //dps.init();   // QFE (Field Elevation above ground level) is set to 0 meters.
  // same as init(MODE_STANDARD, 0, true);

  //dps.init(MODE_STANDARD, 101850, false);  // 101850Pa = 1018.50hPa, false = using Pa units
  // this initialization is useful for normalizing pressure to specific datum.
  // OR setting current local hPa information from a weather station/local airport (QNH).

  dps.init(MODE_ULTRA_HIGHRES,5366, true);  // 53.66 meters, true = using meter units (176' Google Earth)
  // this initialization is useful if current altitude is known,
  // pressure will be calculated based on TruePressure and known altitude.

  // note: use zeroCal only after initialization.
  // dps.zeroCal(101800, 0);    // set zero point
}
void loop()
{
  while (Serial1.available())
  {
    gps.encode(Serial1.read()); // process gps messages
  }
  if(timeStatus()!= timeNotSet)
  {     
    if( now() != prevDisplay) //update the display only if the time has changed
    {
      prevDisplay = now();
      digitalClockDisplay(); 
    }
  }
}

void digitalClockDisplay()
{  // digital clock display of the time
  //myGLCD.setColor(255,255,255);
  myGLCD.print("Date :",8 ,12);  // Print date label
  myGLCD.printNumI(month(),64,12,2,'0'); // Prints 2 digit month with leading 0
  myGLCD.print("/",80 ,12);  //
  myGLCD.printNumI(day(),88,12,2,'0');  // Prints 2 digit day with leading 0
  myGLCD.print("/20",104,12);
  myGLCD.printNumI(year(),112,12); // Print the Year
  myGLCD.print("Time :",8 ,24);  // Print Time label
  myGLCD.printNumI(hourFormat12(),64,24,2,'0'); // Prints 2 digit 12 hour format with leading 0
  myGLCD.printNumI(minute(),84,24,2,'0');
  myGLCD.printNumI(second(),104,24,2,'0');
  myGLCD.print("RH % :",8 ,36);   // Print weather info labels
  //myGLCD.print(" : % RH",94 ,36);
  myGLCD.print("Baro :",8 ,48);  // Print weather info labels
  myGLCD.print(":InHg",102 ,48);
  myGLCD.print("Temp :",8 ,60);
  myGLCD.print("Temp :",8 ,72);
  myGLCD.print(":DegF",102 ,60);
  myGLCD.print(":DegC",102 ,72);

  if (isAM())
  {
    myGLCD.setColor( 0,180, 0);  //set rect line color for AM indicator color
    myGLCD.drawRect(0, 6, 150,90);
    myGLCD.setColor(255,255,255);
    myGLCD.print(":AM",120,24);
  } 
  if(isPM())
  {
    //fillScr(180,180,180);
    myGLCD.setColor( 0, 0,180);  //set rect line color for PM indicator color
    myGLCD.drawRect(0, 6, 150,90); //draw a line 4 lines away from text  ***78
    myGLCD.setColor(180,180,180);  //Set text color
    myGLCD.print(":PM",120,24);
  }
  {
    dps.getPressure(&Pressure);    // Get Barimetric data +/- 1% accurate, in Millibars X 10
    dps.getAltitude(&Altitude);    // get Altimeter Data... Call doesn't return good data
    dps.getTemperature(&Temperature);     // Get Temperature Data +/- 1% accurate, Deg. C X 10

    Temperature = Temperature +2 ;  //Calibration factor for fine temp cal
    Far = (((Temperature  * 18) + 3200) / 10);   // Far(enheit) conversion X 10
   
    Pressure = ((2953 * Pressure) / 100000); // Comvert  Pressure in Millibars X 10 to In/Hg X 10
    Pressure = Pressure - 22 ;   // Pressure Calibration adjustment subtracts .2 In/Hg
   
    float PreS = (Pressure / 100.0);
    float TemP = (Far/10.0);
    myGLCD.printNumF(PreS,2,64 ,48);
    myGLCD.printNumF(TemP,2,64 ,60);
   // myGLCD.printNumF(t,2,64 ,90);
    float h = dht.readHumidity();
    float t = dht.readTemperature();

    // check if returns are valid, if they are NaN (not a number) then something went wrong!
    if (isnan(t) || isnan(h))
    {
      h = 00.0;
      myGLCD.printNumF(h,2,64 ,36);
    }
    else
    {
      myGLCD.printNumF(h,2,64 ,36);
     myGLCD.printNumF(t,2,64 ,72);
    }

  }
}
time_t gpsTimeSync()  //  returns time if avail from gps, else returns 0 
{
  unsigned long fix_age = 0 ;
  // OK TO HERE
  gps.get_datetime(NULL,NULL, &fix_age);
  // unsigned long time_since_last_fix;  // **********COMMENTING THIS WAS DUMB...*************
  //if(fix_age < 1000)                   // ******BUT THIS******
  return gpsTimeToArduinoTime(); // return time only if updated recently by gps 
  //return 0;                            // ******AND THIS MAKES IT WORK, WHY??******
}

time_t gpsTimeToArduinoTime() 
{ // returns time_t from gps date and time with the given offset hours
  tmElements_t tm;
  int year;
  gps.crack_datetime(&year, &tm.Month, &tm.Day, &tm.Hour, &tm.Minute, &tm.Second,NULL,NULL );
  tm.Year = year - 1970;
  time_t time = makeTime(tm);
  return time + (offset * SECS_PER_HOUR);
}

Comments and suggestions are humbly requested. I can cut and paste fairly well. I've learned enough C and C++ from a cold start in march to get this far.

Bob
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: nickgammon on Oct 15, 2012, 06:28 am
Code: [Select]

  Wire.begin();    // Start Wire (IIC)
  delay(1000);    // Waait for IIC to init.


You don't need to wait for I2C to initialize. I never do.




Code: [Select]

  myGLCD.print("Baro :",8 ,48);  // Print weather info labels
  myGLCD.print(":InHg",102 ,48);
...


You can save RAM by keeping these in Program Memory, eg.

Code: [Select]

  myGLCD.print(F("Baro :"),8 ,48);  // Print weather info labels
  myGLCD.print(F(":InHg"),102 ,48);


I'm not sure if it works here but it should.




Code: [Select]

  if (isAM())
  {
    myGLCD.setColor( 0,180, 0);  //set rect line color for AM indicator color
    myGLCD.drawRect(0, 6, 150,90);
    myGLCD.setColor(255,255,255);
    myGLCD.print(":AM",120,24);
  } 
  if(isPM())
  {
    //fillScr(180,180,180);
    myGLCD.setColor( 0, 0,180);  //set rect line color for PM indicator color
    myGLCD.drawRect(0, 6, 150,90); //draw a line 4 lines away from text  ***78
    myGLCD.setColor(180,180,180);  //Set text color
    myGLCD.print(":PM",120,24);
  }


If it isn't AM what else would it be?

How about:

Code: [Select]

  if (isAM())
    {
    myGLCD.setColor( 0,180, 0);  //set rect line color for AM indicator color
    myGLCD.drawRect(0, 6, 150,90);
    myGLCD.setColor(255,255,255);
    myGLCD.print(":AM",120,24);
    } 
  else
    {
    //fillScr(180,180,180);
    myGLCD.setColor( 0, 0,180);  //set rect line color for PM indicator color
    myGLCD.drawRect(0, 6, 150,90); //draw a line 4 lines away from text  ***78
    myGLCD.setColor(180,180,180);  //Set text color
    myGLCD.print(":PM",120,24);
    }
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Docedison on Oct 15, 2012, 07:08 am
Is this the cause it appears to be the address to the var fix age
"gps.get_datetime(NULL,NULL, [font=Verdana]&fix_age);" [/font]
and this:
"if(fix_age < 1000)" shouldn't there be a dereference to &fix_age or do I need to go back 50 pages and read the several lessons again... I just noticed this and wondered about it as this was the beginning of my morning reading topic. Have only read the first 10 pages or so.

Bob
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: nickgammon on Oct 15, 2012, 07:55 am
Look at the prototype:

Code: [Select]

// date as ddmmyy, time as hhmmsscc, and age in milliseconds
  void get_datetime(unsigned long *date, unsigned long *time, unsigned long *age = 0);


The function get_datetime is expecting unsigned long pointers (see the asterisks).

Thus you are correct in passing &fix_age which is a pointer to the unsigned long fix_age.

But afterwards the variable is a simple variable. You don't dereference it. You dereference pointers, eg.

Code: [Select]

  unsigned long fix_age = 0 ;
  unsigned long * ptr_fix_age = &fix_age ;

  gps.get_datetime(NULL,NULL, ptr_fix_age);


In this case the variable ptr_fix_age is a pointer (see the asterisk) and its value is &fix_age because the "&" operator takes the address of the thing it is next to.

Now, you could either say:

Code: [Select]

if(fix_age < 1000)


or:

Code: [Select]

if(*ptr_fix_age < 1000)


If you use the pointer you dereference it. If not, you don't.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: bvenneker on Oct 31, 2012, 10:35 pm

I got the same errors here with arduino 18, 22 and 1.01. and different Time lib versions.

/usr/share/arduino/libraries/Time/DateStrings.cpp:18:18: error: variable 'monthStr1' must be const in order to be put into read-only section by means of '__attribute__((progmem))'

The fix for my debian system was:

go back to gcc-avr version 4.3.5-1 * and
go back to avr-libc version 1.6.8-2 *

Now everything compiles just fine

* i updated to gcc-avr 4.7.0-2 and avr-libc 1.8.0-2 which broke compiling TIME libs.

Having fun again
Jan


Same issue after updating to lubuntu 12.10 (not sure if that is related..)

To fix this, I think it's better to fix the actual error in stead of using an older compiler that ignores the error.
The compiler says the variables in DateStrings.cpp must be constants so we can fix this if we declare them as contants.

See the attachment for the new file

example on the changes that should be made:

This:
char monthStr1[] PROGMEM = "January";
should be:
const char monthStr1[] PROGMEM = "January";
Make the same change on many lines..

And this (on lines 31 and 48)
PGM_P monthNames_P[] PROGMEM = ... etc
should be
PGM_P const monthNames_P[] PROGMEM = ... etc

I'll try to find out how to submit this change into the official release

Bye !
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: grantusmaximus on Nov 08, 2012, 02:00 am
I believe the following page would benefit from some additional info - http://www.arduino.cc/playground/Code/time

i.e. now( ) returns the number of seconds elapsed since midnight 1/1/1970

As a newbie to Arduino, but with lots of programming experience elsewhere. I was looking for a function which did this but it took me a awhile before I realised what now() returned...  :smiley-red:
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Docedison on Nov 08, 2012, 06:34 am
As much as I dislike repeating myself... read the header files for any lib you use, that is where the function prototypes are... Lots of Good Stuff there

Bob
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: chickenturd on Nov 22, 2012, 09:49 am
Excuse me if this has been brought up before, but the TimeAlarms library doesn't have Arduino version check and fails on my Arduino. The Time library does, so I just used it as an example to fix my local TimeAlarms library.

In TimeAlarms.cpp:

Code: [Select]
#include <WProgram.h>

in Time.cpp:

Code: [Select]
#if ARDUINO >= 100
#include <Arduino.h>
#else
#include <WProgram.h>
#endif


I will be publishing a how-to for my Arduino project and step one for the end user will be to download the Time/TimeAlarm library, so I don't want them to have problems like i did.

Thanks yall for writing this library, I really enjoy it!
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Docedison on Nov 23, 2012, 04:03 am
Actually the point is of little real interest,. Although it is a good thing that you know how to do it, most who have that issue... Don't come here and post questions.
One thing more the TimeGPS.ino sketch doesn't work. I have one that is working OK but I've not had a chance to post it yet. I did a project that uses a 3.2" 320 X 240 display, a BMP085 barometer and an AMS  2302 hygormeter with TimeGPS for a 'mini' weather station.

Bob
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: liseman on Dec 10, 2012, 08:08 pm
As per below, the following change should be made to TimeAlarms.cpp :

replace:
#include <WProgram.h>
with:
#if ARDUINO >= 100
#include <Arduino.h>
#else
#include <WProgram.h>
#endif

This change has been made and released in Time.cpp .

2 of the errors I encountered before making this change were:
- In member function 'void TimeAlarmsClass::delay(long unsigned int)':
- error: 'millis' was not declared in this scope

Is there somewhere else I should submit this, too?


Excuse me if this has been brought up before, but the TimeAlarms library doesn't have Arduino version check and fails on my Arduino. The Time library does, so I just used it as an example to fix my local TimeAlarms library.

In TimeAlarms.cpp:

Code: [Select]
#include <WProgram.h>

in Time.cpp:

Code: [Select]
#if ARDUINO >= 100
#include <Arduino.h>
#else
#include <WProgram.h>
#endif


I will be publishing a how-to for my Arduino project and step one for the end user will be to download the Time/TimeAlarm library, so I don't want them to have problems like i did.

Thanks yall for writing this library, I really enjoy it!
Title: Alarm.alarmRepeat at midnight
Post by: Guy-Wittig on Jan 01, 2013, 12:18 am
Hi

Not sure if you are aware of this, but alarmRepeat does not work for midnight. E.G.

Alarm.alarmRepeat(0,0,0,myHandler); // This does not call myHandler

I found I had to set the alarm for 1 sec past midnight for it to work.

Alarm.alarmRepeat(0,0,1,myHandler); // This does call myHandler


Guy
Title: Re: Alarm.alarmRepeat at midnight
Post by: mem on Jan 01, 2013, 05:05 am

Not sure if you are aware of this, but alarmRepeat does not work for midnight. E.G.


Hi Guy,

0,0,0 is currently ignored by the alarm code. I am traveling at the moment so can't test any code changes, but you are welcome to try the following:

In the updateNextTrigger() function in TimeAlarms.cpp, change :
  if( (value != 0) && Mode.isEnabled )
to:
  if( Mode.isEnabled )  // remove check for value != 0
Title: Time and TimeAlarms Libraries – Overflow of millis()
Post by: tdf11 on Jan 27, 2013, 07:34 pm
Hey all,

I have a question regarding the function time_t now() inside the time library:
Inside this function the Arduino built-in timer ( millis() ) is compared to a last update time of the library.
I wonder what will happen after approx. 50 days of operation when the number returned by millis() has an overflow.

As far as I understood the code, the time will stay at its last update time and will not run anymore.
Did anyone observe such a behaviour or is there a certain function which takes care about such an overflow which I did not recognize?

Thanks,
Thomas

Code: [Select]
time_t now(){
  while( millis() - prevMillis >= 1000){     
    sysTime++;
    prevMillis += 1000;
#ifdef TIME_DRIFT_INFO
    sysUnsyncedTime++; // this can be compared to the synced time to measure long term drift     
#endif
  }

... 

  return sysTime;
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: nickgammon on Jan 27, 2013, 10:15 pm
millis will wrap around after 50-odd days. It doesn't stop, or not run.

If you do subtraction that wrap-around won't matter.

eg.

Code: [Select]

if (millis () - startTime >= wantedInterval)
 {
 // do something
 }

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: fallahi on Jan 29, 2013, 11:01 pm
What will happen if you have the following:
  Alarm.alarmRepeat(8,30,0, AlarmA);
  Alarm.alarmRepeat(8,30,0, AlarmB);
  Alarm.alarmRepeat(8,30,0, AlarmC);

Will AlarmA get executed 1st, and then AlarmB and then AlarmC? 

Does the accuracy of the time, depends on other program running, or it has to be idle?  In another words, Do I need to add delay(1) or something like that in my loop? 

Does the time accuracy changes when used with other libraries like PulsePattern?
http://playground.arduino.cc//Main/PulsePattern

Thank you.
Sia
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mem on Jan 29, 2013, 11:29 pm
Alarms for the same time will be called in the order the were scheduled.

The scheduler calls the alarm handler in the Alarm.delay function so this should be called regularly in the sketch. There is a readme file in the download with some more details.
When there are more than one alarm ready to be triggered, the first scheduled alarm is serviced on the next call to Alarm.delay, the next scheduled alarm is serviced on the next call to Alarm.delay and so on.
The accuracy of the servicing depends on how often the Alarm.delay function is called.   

I have not used PulsePattern, but if time the code is in the interrupt handler is short, the timing accuracy should not be significantly affected. Why not give it a try. If you print the millis value in the alarm handler you should be able to see if that library is affecting the servicing of the alarms.

I hope that helps.

Have fun!
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: fallahi on Jan 30, 2013, 12:42 am
Thank you Mem.  It was very helpful. 

I have been successfully use Alarm.timerRepeat(1, DisplayTime) and it seems to work correctly. Showing "millies" is a great idea, thank you.  I will add that to my code. 

Within my routine, it fetches something from the network, Reading some huge file, and parse and filter what it receives.  I have this done every one minute with Alarm.timerRepeat(60, ReadData).  The problem is when the data is being read, the DisplayClock does not seem to be executed (Clock stops), for 10~20 seconds.  When its done with the ReadData code, it goes back and show the clock every second and the time seems to be correct. 

With in ReadData code, I am using Alarm.delay, client.connect and some other functions from Ethernet library. 

The PulsePattern works on Timer1.  I will give that a try. 

Thanks again. 
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: keith66 on Feb 01, 2013, 05:05 pm
I am a beginner with arduino.
I have a funcioning lcd 20x4 with rtc module after a long time getting the correct libraries to work with arduino1.0.3.
this display the time & date ect but I now need to add alarm functions etc.
the working DS1307library i am using is called DS1307new and my code based on the below that came with library

Scriptname : DS1307_Test.pde
// # Author     : Peter Schmelzer, Oliver Kraus
// # Date       : 2011-04-08
// # Version    : 1.21

I would like to use the alarmtime library and have downloaded the time library from arduino playground but all the programs give compile errors.
I have removed all other libraries to check incase there was any conflicting ones but still does not work.

The above code and library is more complex than the code in the time library and would prefer to use that if possible.

Any help would be appreciated
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Feb 01, 2013, 05:08 pm
Once you downloaded the code, it became yours. You need to post YOUR code and YOUR error messages.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mem on Feb 01, 2013, 05:24 pm
Keith, there is code for connecting to a DS1307 RTC provided with the Time library download, its called TimeRTC. Why not use that?

Michael
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Feb 01, 2013, 06:17 pm

Keith, there is code for connecting to a DS1307 RTC provided with the Time library download, its called TimeRTC. Why not use that?

Michael

Well, well. Look who's back. Been a while. Life treating you well, I hope.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mem on Feb 01, 2013, 06:53 pm

Well, well. Look who's back. Been a while. Life treating you well, I hope.


Hi Paul, its good to be back.
I have been busy with all kinds of interesting projects. Still am, but will try to hang out here as much as possible.

Michael
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: keith66 on Feb 03, 2013, 10:11 pm

Keith, there is code for connecting to a DS1307 RTC provided with the Time library download, its called TimeRTC. Why not use that?

Michael


Yes I have tried that but I can´t get any of the code to work of the official time library download, any ideas
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: keith66 on Feb 03, 2013, 10:20 pm
just to illustrate I have just opened TimeRTC from examples/time/time/examples and tried to compile it. I have not touched this code. I just gave the other code so you were aware of what was working, I can post the whole code but becomes rather long.
I'm sure the solution if something simple but can't get it.
It seems to me it is not picking up the library but yet it is in the right place and in shown in examples.. thanks for any help. the errors in compiling shown below.


TimeRTC.pde: In function 'void setup()':
TimeRTC:13: error: 'RTC' was not declared in this scope
TimeRTC:13: error: 'setSyncProvider' was not declared in this scope
TimeRTC:14: error: 'timeStatus' was not declared in this scope
TimeRTC:14: error: 'timeSet' was not declared in this scope
TimeRTC.pde: In function 'void digitalClockDisplay()':
TimeRTC:28: error: 'hour' was not declared in this scope
TimeRTC:29: error: 'minute' was not declared in this scope
TimeRTC:30: error: 'second' was not declared in this scope
TimeRTC:32: error: 'day' was not declared in this scope
TimeRTC:34: error: 'month' was not declared in this scope
TimeRTC:36: error: 'year' was not declared in this scope
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mem on Feb 03, 2013, 11:13 pm
It looks like the libraries are not being found.
Make sure you have installed DS1307RTC in the Arduino libraries folder.

The Time.zip file is structured so you can copy the three folders (Time, TimeAlarms, and DS130RTC) into the Arduino Libraries folder.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: keith66 on Feb 04, 2013, 10:41 am
Yes that what it seems like to me yet all the folders were unzipped correctly in the library folder.
I've taken the screen shot to show
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Feb 04, 2013, 03:13 pm
The Time, TimeAlarms, and DS1307RTC folders all go at the same level. DS1307RTC does not go in the Time folder.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: keith66 on Feb 04, 2013, 11:00 pm
Yes how stupid thanks may be back later if i can't get my head around the alarms, thanks again keith
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mem on Feb 05, 2013, 08:42 am
Keith, don't beat yourself up. I can see why it seemed logical to include the TimeAlarm library within the Time folder. Unfortunately, Arduino does not currently handle library installation or inter-library dependencies very well, which  is why I chose to have TimeAlarms as a separate library. Perhaps when Arduino support a simple mechanism for installing libraries, problems such as yours will go away.

Michael
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: dalai on Feb 13, 2013, 04:51 pm
How is "adjustTime(adjustment);" command used ?

I want to  send a command to my program ,so an hour or a day is added to timer.
Later those commands will be sent by the press of a button

Is this command ok ? adjustTime(hour()++);
Code: [Select]
#include <Time.h> 


void setup()  {
  Serial.begin(9600);

  Serial.println("sending time to arduino");
  setTime(0,0,0,1,1,2000);
}

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

void digitalClockDisplay(){

  Serial.print(day());
  Serial.print(" ");
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print(" ");
  Serial.print(day());
  Serial.print(" ");
  Serial.print(month());
  Serial.print(" ");
  Serial.print(year());
  Serial.println();
}

void printDigits(int digits){
   Serial.print(":");
  if(digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: larryd on Feb 14, 2013, 07:51 am
Quote
I want to  send a command to my program ,so an hour or a day is added to timer.

When you detect the command you can use the following:

time_t t  = now();
setTime(t + X );                     //X would be 3600 for 1 hour or 86400 for 1 day

OR

adjustTime(X) ;                     //X is + or - moves the time ahead or back X seconds ex: +3600 or -3600
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Krodal on Mar 07, 2013, 03:09 pm
DS1302

Hello Michael,
I placed this code in a class: http://playground.arduino.cc//Main/DS1302
And I could add the 'get', 'set', 'read' and 'write' functions.

But I don't understand the difference between the 'sysTime' and the time in the RTC.
Are they synchronized with the 'syncInterval' ?
If the Arduino is running a little slow, it is no problem.
If the Arduino is running a little faster, it could cause a glitch for the number of seconds.

How is this handled ?
I do not know how this is done in a PC or other embedded system. I was just wondering what would happen.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Derkatwork on Mar 11, 2013, 02:05 am
I'm attempting to use the Time.h library in a program, but the program won't compile due to an issue in the .cpp file:


/Users/.../libraries/Time/Time.cpp: In function 'time_t now()':
/Users/.../libraries/Time/Time.cpp:240: error: 'millis' was not declared in this scope
/Users/.../libraries/Time/Time.cpp: In function 'void setTime(time_t)':
/Users/.../libraries/Time/Time.cpp:268: error: 'millis' was not declared in this scope

I'm not an expert, so I'd rather not go digging in the library files.  I just updated to 1.0.3 from what I assume was the beta version.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Mar 11, 2013, 12:09 pm
Quote
I just updated to 1.0.3

Have you updated the Time library, too? Change WProgram.h to Arduino.h in the header and/or source file(s).
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Derkatwork on Mar 12, 2013, 01:11 am
Thank you very much.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: djlamm on Apr 03, 2013, 08:37 pm
Hello everyone,  I'm trying to use the Arduino time library at http://playground.arduino.cc/Code/Time in my code, but the download link brings me to a page that says "The page "Time/Zip" doesn't exist."

Anyone know where I can download this library?

Thanks.
David
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: djlamm on Apr 04, 2013, 04:21 pm

Anyone know where I can download this library?


Looks like the problem is fixed as of this morning.  Thanks.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: JuraKa on Apr 07, 2013, 11:38 pm
I just downloaded new update of Time library. When I try to compile it gives me an error:
sketchbook/libraries/Time/DateStrings.cpp:41:56: error: variable 'monthNames_P' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
sketchbook/libraries/Time/DateStrings.cpp:58:54: error: variable 'dayNames_P' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
sketchbook/libraries/Time/DateStrings.cpp:59:51: error: variable 'dayShortNames_P' must be const in order to be put into read-only section by means of '__attribute__((progmem))'

It is due to new gcc-avr version 4.7.1

Three lines of code in DateStrings.cpp in library should be replaced by:
line 41: PGM_P PROGMEM monthNames_P[] =
line 58: PGM_P PROGMEM dayNames_P[] = { dayStr0,dayStr1,dayStr2,dayStr3,dayStr4,dayStr5,dayStr6,dayStr7};
line 59: const char dayShortNames_P[] PROGMEM = "ErrSunMonTueWedThrFriSat";

It, at least, compiles fine. There is no need to downgrade gcc-avr as suggested in several posts.

If someone come across the same problem, I hope it will helps.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: editor1979 on Apr 08, 2013, 04:47 pm
Hello,
I'm sorry if this has been covered but I couldn't find it.
I modified the 'TimeSerialDateStrings' to include a 16x2 I²C LCD Display.
It seems to display okay for a minute, but then seems to get erroneous data causing it to display incorrect information.

It would start off displaying:
10:38:16 Mon
Apr 08, 2013

but after a minute it would change to something seemingly random like:
21:11:26 Fri
Aug 29, 2104

and it doesn't do this once. I haven't been able to get a time interval of when these errors occur, but if I could get some help fixing them, it would be appreciated. I have also seen it display years that contain 5 digits. That may have been an alignment issue tho.

Code: [Select]
/*
* TimeSerialDateStrings.pde
* example code illustrating Time library date strings
*
* This sketch adds date string functionality to TimeSerial.pde
*
*/

#include <Time.h> 
#include <Wire.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(0); //I²C

#define TIME_MSG_LEN  11   // time sync to PC is HEADER followed by unix time_t as ten ascii digits
#define TIME_HEADER  'T'   // Header tag for serial time sync message
#define TIME_REQUEST  7    // ASCII bell character requests a time sync message

void setup()  {
  lcd.begin(16,2);lcd.setBacklight(HIGH);
  Serial.begin(9600);
  setSyncProvider( requestSync);  //set function to call when sync required
  Serial.println("Waiting for sync message");
}

void loop(){   
  if(Serial.available() )
  {
    processSyncMessage();
  }
  if(timeStatus()!= timeNotSet)
  {
    digitalClockDisplay(); 
  }
  //delay(1000); //Disabled because I am not sending time to the Serial Monitor.
                 //I'm sending it to an LCD and the 1 second delay causes it to apear like it skips 1 second every 11 seconds even tho it really doesn't.
}

void digitalClockDisplay(){
  // digital clock display of the time
  lcd.setCursor(2,0);
  printDigits(hour());
  lcd.setCursor(4,0);
  lcd.print(":");
  lcd.setCursor(5,0);
  printDigits(minute());
  lcd.setCursor(7,0);
  lcd.print(":");
  lcd.setCursor(8,0);
  printDigits(second());
  lcd.print(" ");
  lcd.print(dayShortStr(weekday()));
  lcd.print(" ");
  lcd.setCursor(2,1);
  lcd.print(monthShortStr(month()));
  lcd.print(" ");
  printDigits(day());
  lcd.print(", ");
  lcd.print(year());
}

void printDigits(int digits){
  // utility function for digital clock display: prints preceding colon and leading 0
  //lcd.print(":"); //seemed to be getting in the way, nut I may be wrong
  if(digits < 10)
    lcd.print('0');
  lcd.print(digits);
}

void processSyncMessage() {
  // if time sync available from serial port, update time and return true
  while(Serial.available() >=  TIME_MSG_LEN ){  // time message consists of a header and ten ascii digits
    char c = Serial.read() ;
    lcd.clear();
    Serial.print(c); 
    if( c == TIME_HEADER ) {       
      time_t pctime = 0;
      for(int i=0; i < TIME_MSG_LEN -1; i++){   
        c = Serial.read();         
        if( c >= '0' && c <= '9'){   
          pctime = (10 * pctime) + (c - '0') ; // convert digits to a number   
        }
      }   
      setTime(pctime);   // Sync Arduino clock to the time received on the serial port
    } 
  }
}

time_t requestSync()
{
  //Serial.print(TIME_REQUEST,BYTE); 
  //return 0; // the time will be sent later in response to serial mesg
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Apr 09, 2013, 01:23 am
Code: [Select]
time_t requestSync()
{
  //Serial.print(TIME_REQUEST,BYTE); 
  //return 0; // the time will be sent later in response to serial mesg
}

A non-void function MUST return a value. Since this is your sync function, the fact that it doesn't return anything is what is screwing up your clock.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: editor1979 on Apr 09, 2013, 04:25 pm
Last night, I got this message. I re-enabled the two lines in question then resent the time code.
I then applied external power and removed the Serial Line and shut down my computer to leave it running without the computer.
It ran all night. I just got home from work and turned on my computer. The Arduino Clock is still in perfect sync with my PC.
It is displaying all the correct information.

Thank you for your help!
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Costin on Apr 10, 2013, 10:00 am
Hi all...I'm working at my first project using Arduino and it's IDE and I want to use a macro which is inside the Time.h..For example,after a reset or a power supply fault to the board, I want to calculate the second of the day when the board recovers, therefore to find in which cycle of a finite state machine the program is..For this I want to use the elapsedSecsToday, but I'm far from knowing how to use it, efectivelly...Here is my code,until now, and I want to run this macro in the set-up sequence..Can you give me a clue how to do it?
Code: [Select]
// GPS + RTC  FSM clock
//
#include "Wire.h"
#include <DS1307RTC.h>
#include <Time.h>       
#include <Timezone.h> //Jack Christensen's Timezone 
#include <TinyGPS.h>//GPS and NewSoftSerial libraries are the work of Mikal Hart
#define DS1307_ADDRESS 0x68


//Timezone settings..=============================.

TimeChangeRule myDST = {
  "ROM", Last, Sun, Mar, 3, +180};    //Daylight time = UTC - 4 hours
TimeChangeRule mySTD = {
  "ROM", First, Sun, Nov, 3, +120};     //Standard time = UTC - 5 hours
Timezone myTZ(myDST, mySTD);
TimeChangeRule *tcr;        //pointer to the time change rule, use to get TZ abbrev
time_t utc, local,t;//var that must be seen by others functions

//Tiny GPS====================================

TinyGPS gps;
boolean valid = false;

//***interrupt*********************
volatile boolean interruptComplete = false;
volatile boolean rtcisrunning = false;


//=========GPS checking=============================================
time_t gpsTimeSync()
{
  unsigned long age = 0 ;   
  unsigned long date, time;
  gps.get_datetime(NULL, NULL, &age);

  //No time update to DS1307 if GPS signal is lost....
  if (age == TinyGPS::GPS_INVALID_AGE || age >1500 ){
    //Serial.println("GPS lost..");
    valid = false;
  }
  else{
    valid = true ;
    gpsToArduino();
  }
}

//  GPS to DS1307 local time =====================================   
time_t gpsToArduino(){
  tmElements_t tm;
  int year;
  gps.crack_datetime(&year, &tm.Month, &tm.Day, &tm.Hour, &tm.Minute, &tm.Second, NULL, NULL);
  tm.Year = year-1970 ;
  time_t time = makeTime(tm);//GPS data--> time_t....
  utc = time;// time from GPS....
  local = myTZ.toLocal(utc, &tcr);
  //RTC.set(local);// moved from here to the loop...

}
// read  a register from DS1307....

void readreg() {
  byte reg;
  Wire.beginTransmission(0x68);              // write the control register
  Wire.write(0x00);                           // register address 07H)
  Wire.endTransmission();

  Wire.requestFrom(0x68, 1);
  reg=Wire.read();
  Serial.println (reg,HEX);
  //delay(1000);
}

//Debug on serial monitor..=================================================
void monitor_out(){
  char dateTime[20];
  sprintf(dateTime, "%4d-%02d-%02d %02d:%02d:%02d", year(),
  month(), day(), hour(),minute(), second()) ;
  Serial.print(dateTime);
  Serial.print(" - day of week: ");
  Serial.println(dayStr(weekday()));
}


//======================================

void getGPS(){
  bool newdata = false;
  //unsigned long start = millis();
  // Every second we print an update
  //while (millis() - start < 1000)
  //{
  if (feedgps()) newdata = true;
  gpsTimeSync();
  //}
}

// ***********************************************
// read GPS serial data and send to tinyGPS
// ***********************************************
static bool feedgps() {
  while (Serial1.available()) {
    if (gps.encode(Serial1.read())) {
      return true;
    }
  }
  return false;
}

//=================================
void setup()
{
  Serial.begin(19200);//monitor
  Serial1.begin(19200); // for GPS
  Serial1.println ("$PMTK314,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*28");//RMC only...
  Serial1.println ("$PMTK220,1000*1F");//fix at 1000 ms
  attachInterrupt(0, interruptHandler, FALLING);
  Wire.begin();
  delay(1000);//debug only..
 
     
      while ( ! valid ){
        getGPS();
      }
         if (valid){
      RTC.set(local);// DS1307 set to the local time from timezone..
      Serial.println ( "DS set");//debug only
      delay(1000);//debug only
      }
    //Serial.println (elapsedSecsToday());
   
 
  setSyncProvider(RTC.get);   // the function to get the time from the RTC
  if(timeStatus()!= timeSet)
    Serial.println("Unable to sync with the RTC");
  else
    Serial.println("RTC has set the system time");
    delay(500);//debug only

   

}
void loop()
{

  if (interruptComplete){

    if (valid){  // If GPS sentence is valid,write the time, if not, skip..

      RTC.set(local);// DS1307 set to the local time from timezone..
      Serial.println ( "beep");//debug only
    }
    if (! valid){
      Serial.println ("No GPS");// Serial2---->Ethernet...
    }
    RTC.get();// time from DS1307...
    monitor_out();   //print it...
    //readreg();
    interruptComplete = false;
  }
  getGPS();// get data from GPS
}


//interrupt vector=============================
void interruptHandler()
{
  rtcisrunning = true;
  interruptComplete = true;

}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: pjrc on Apr 10, 2013, 11:37 am

It is due to new gcc-avr version 4.7.1

Three lines of code in DateStrings.cpp in library should be replaced by:
line 41: PGM_P PROGMEM monthNames_P[] =
line 58: PGM_P PROGMEM dayNames_P[] = { dayStr0,dayStr1,dayStr2,dayStr3,dayStr4,dayStr5,dayStr6,dayStr7};
line 59: const char dayShortNames_P[] PROGMEM = "ErrSunMonTueWedThrFriSat";


Please email me directly, paul at pjrc dot com.  I will apply this fix, but only if you (or someone) using avr gcc 4.7.1 will work with me by email to help with testing.

I do not plan to work on Time or other libraries until after Arduino 1.0.5 releases.

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Costin on Apr 11, 2013, 06:34 am
Hi..Any help for me? Post#164... :)
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: JamesBee on Apr 21, 2013, 07:20 pm
I'm new to Arduino. I'm actually using a Seeeduino Stalker v2.3 for a project that monitors the output from a tipping water gauge. I've put the Time and Time Alarm libraries into the project which was already logging to a text file on an SD card, so far so good. What I noticed immediately on adding the timers and alarms in is that in testing at least that the logging was no longer triggering every time the gauge, which is a reed switch, was tripped. When I comment out the 'Alarm.delay(1000)' and reload the project to the device the logging works fine. With the alarm on, the logging is sporadic at best.

Looking for some help and a little insight on how I might do this better. Maybe the reed switch / logging method needs to be interrupt driven? Appreciative of help and suggestions.

James

code:  

Code: [Select]

#include <Wire.h>
#include <SD.h>
#include "DS3231.h"
#include "DS1307RTC.h"
#include "Time.h"
#include "TimeAlarms.h"

 const int chipSelect = 10;

 int Led_Pin = 13;   // choose the pin for the LED
 int Sensor_Pin = 6; // choose the Sensor_Pin
 int val = 0;        // variable for reading the Sensor_Pin status
 String logData[] = ""; //empty string for log data
 DS3231 RTC2; //Create the R8025 object

void setup()
{
Serial.begin(9600);
Wire.begin();
setTime(12,39,45,21,04,2013);
Alarm.alarmRepeat(12,41,0, DailyLog);
Alarm.timerRepeat(15, Repeater);

pinMode(Led_Pin, OUTPUT);
pinMode(Sensor_Pin, INPUT);
 /* add setup code here */
setupsdcard();
initializelogfile();


}


void loop()
{
Alarm.delay(1000);
logging();
}

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

void DailyLog(){
 Serial.println("Alarm: - sending log file");    
}

void setupsdcard(){
 pinMode(10, OUTPUT);
 if (!SD.begin(chipSelect)) {
   return;
 }
}


void logging(){
 
  val = digitalRead(Sensor_Pin);  // read Sensor_Pin
 if (val == HIGH) {        
   digitalWrite(Led_Pin, LOW);
 } else {
   digitalWrite(Led_Pin, HIGH);  //Set Led high
     logdata();
 }
}

void initializelogfile(){
    char* filename = "datalog.txt";
    if(!SD.exists(filename)){
       Serial.println("Creating new datalog.txt...");
       File NewdataFile = SD.open(filename, FILE_WRITE);
       NewdataFile.close();
    }
}

void logdata(){
 
   File myFile = SD.open("datalog.txt", FILE_WRITE);
   if (myFile) {
     time_t t = now();
 int32_t temp = RTC2.getTemperature();
 String aDate = String(year(t), DEC) + "/" + String(month(t), DEC) + "/" + String(day(t), DEC) + ":" + String(hour(t),DEC) + ":" + String(minute(t), DEC) + ":"+ String(second(t),DEC) + " temp:" + temp + "'C";
     myFile.println(aDate);
     myFile.close();
     Serial.println(aDate);
     delay(500); } else {
   }
}

void getdata(){
 File myFile = SD.open("datalog.txt");
 
 if (myFile) {
   int counter = 0;
   while (myFile.available()) {
      logData[counter] = String(myFile.println());
     
  Serial.write(sizeof(logData));
      counter++;
   }
   myFile.close();
 } else {
   Serial.println("error opening DATALOG.TXT");
 }
 
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Apr 21, 2013, 11:46 pm
Why are you constructing and destructing so many String objects just to write the date to the file? Use sprintf() and a fixed buffer or 6 calls to File::print() and quit pissing memory away.

Code: [Select]
    while (myFile.available()) {
       logData[counter] = String(myFile.println());

This makes no sense whatsoever. Printing a blank line to the file, and then storing the number of characters printed to the file, wrapped in a String, in an array makes no sense.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: JamesBee on Apr 22, 2013, 12:01 am
Good point. I'm not entirely focused on performance just yet, more on getting it to work, which I just managed to do. The original intent of that method was to get the file content, read it line by line, get the first and last log entry, check the date difference to establish the time span and then based on that, process the file and send it as an SMS message. All that being said, it's no longer relevant.

Thanks for the pointers on memory and sprintf() etc. I'll keep it in mind as the project moves forward and I get into making better use of the limited resources on the device.

===
Code: [Select]

#include <Wire.h>
#include <SD.h>
#include "DS3231.h"
#include "DS1307RTC.h"
#include "Time.h"
#include "TimeAlarms.h"
#include <SoftwareSerial.h>
#include <String.h>

 SoftwareSerial mySerial(7, 8);
 const int chipSelect = 10;
 int switchPin = 2; // choose the Sensor_Pin
 int counter0 = 0;
 long lastDebounce = 0;
 long debounceDelay = 500;
 int val = 0;        // variable for reading the Sensor_Pin status
 String logData[] = ""; //empty string for log data
 DS3231 RTC2; //Create the R8025 object
 int32_t temp = 0;

void setup()
{
mySerial.begin(19200);
Serial.begin(9600);
Wire.begin();
setTime(12,39,45,21,04,2013);
Alarm.alarmRepeat(12,41,0, DailyLog);
Alarm.timerRepeat(15, Repeater);
pinMode(switchPin, INPUT);
//digitalWrite(switchPin, HIGH);
attachInterrupt(0, trigger0, FALLING);
 /* add setup code here */
setupsdcard();
initializelogfile();
delay(500);
}

void loop()
{
Alarm.delay(1000);
temp = RTC2.getTemperature();
}

void trigger0(){
if((millis() - lastDebounce) > debounceDelay){
counter0++;
File myFile = SD.open("datalog.txt", FILE_WRITE);
if (myFile) {
 time_t t = now();
 String aDate = String(year(t), DEC) + "/" + String(month(t), DEC) + "/" + String(day(t), DEC) + ":" + String(hour(t),DEC) + ":" + String(minute(t), DEC) + ":"+ String(second(t),DEC)+ " " + temp + "'c";
 myFile.println(aDate);
 myFile.close();
 Serial.println(aDate);
 delay(200);
} else {
}
lastDebounce = millis();
}
}

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

void DailyLog(){
 Serial.println("Alarm: - sending log file");  
   if (Serial.available())
   switch(Serial.read())
  {
    case 't':
      SendTextMessage();
      break;
  }
 if (mySerial.available())
   Serial.write(mySerial.read());
}

///SendTextMessage()
///this function is to send a sms message
void SendTextMessage()
{
 mySerial.print("AT+CMGF=1\r");    //Because we want to send the SMS in text mode
 delay(100);
 mySerial.println("AT + CMGS = \"+86138xxxxx615\"");//send sms message, be careful need to add a country code before the cellphone number
 delay(100);
 mySerial.println("A test message!");//the content of the message
 delay(100);
 mySerial.println((char)26);//the ASCII code of the ctrl+z is 26
 delay(100);
 mySerial.println();
}

void setupsdcard(){
 pinMode(10, OUTPUT);
 if (!SD.begin(chipSelect)) {
   return;
 }
}

void initializelogfile(){
    char* filename = "datalog.txt";
    if(!SD.exists(filename)){
       Serial.println("Creating new datalog.txt...");
       File NewdataFile = SD.open(filename, FILE_WRITE);
       NewdataFile.close();
    }
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Apr 22, 2013, 01:57 am
Quote
SoftwareSerial mySerial(7, 8);     

Ah, yes, the infamous smiley face pin. I wish my Arduino had one.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: JamesBee on Apr 22, 2013, 06:38 pm
Ah yes, the smiley. Where would we be without it? Likely living in caves and chipping pointy stones... no, wait a minute, forget that.

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: biggosh on Apr 27, 2013, 02:46 pm
The changes work also on avr-gcc 4.7.2
thanks
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: iwilllearn on May 20, 2013, 03:44 am
adjustTime(adjustment); // Adjust system time by adding
                         //  the adjustment value
help
how do i use this function?
what is the adjustment value?
thank you
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: kgarner on May 22, 2013, 04:25 pm
Hi.. new with Arduino R3 and official Ethernet shield I was very pleased to use the TimeNTP Example and have it work first time. That is when I - Ethernet.begin(mac) - address only and connect to my network using DHCP. However, when I specify the IP address it fails each time with "No NTP Response :-(".

I really need to be able to specific a static address but even when I also supply the gateway address and subnet mask - Ethernet.begin(mac, IP, Gateway, Subnet); - it never works. How can I fix this please?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Docedison on May 30, 2013, 07:24 am
While the Time Library is ok... it really doesn't work like it had been tested... The TimeGPS code is completely non functional. No surprise, it was written on 1/6/2010 and never tested. Ever.

Doc
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Elektrix on Jul 02, 2013, 11:06 pm
I have gcc-avr 4.7.2 on Debian Wheezy and tried the Time library. I got the same errors as already mentioned. Then I changed DateStrings.cpp as shown above. Still got the same errors. Now I take the original version from the playground, works ok.

Elektrix
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: pjrc on Jul 03, 2013, 12:38 am
Download Arduino from www.arduino.cc and use it, instead of the one provided by your distro.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PedroS23 on Jul 17, 2013, 06:32 pm
The results appear in Serial.Monitor this:

(http://img706.imageshack.us/img706/7207/c12u.png) (http://imageshack.us/photo/my-images/706/c12u.png/)


I wonder if it is possible to set the date and time displayed for the Date and Current Time????

example:

17/07/2013 17:10:00


I'm printing that results in the void loop () (as shown in the code previously published) and was taken from a line of code that I took from the window where I downloaded the library team, and this is the code I'm using:

Code: [Select]

*
* TimeSerial.pde
* example code illustrating Time library set through serial port messages.
*
* Messages consist of the letter T followed by ten digit time (as seconds since Jan 1 1970)
* you can send the text on the next line using Serial Monitor to set the clock to noon Jan 1 2013
T1357041600 
*
* A Processing example sketch to automatically send the messages is inclided in the download
* On Linux, you can use "date +T%s > /dev/ttyACM0" (UTC time zone)
*/

#include <Time.h> 

#define TIME_HEADER  "T"   // Header tag for serial time sync message
#define TIME_REQUEST  7    // ASCII bell character requests a time sync message

void setup()  {
  Serial.begin(9600);
  while (!Serial) ; // Needed for Leonardo only
  pinMode(13, OUTPUT);
  setSyncProvider( requestSync);  //set function to call when sync required
// Serial.println("Waiting for sync message"); [i][b]it's necessary???[/b][/i]
time_t t = now(); // Store the current time in time
                    //  variable t
now();
}


void digitalClockDisplay(){
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print(" ");
  Serial.print(day());
  Serial.print(" ");
  Serial.print(month());
  Serial.print(" ");
  Serial.print(year());
  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);
}


void processSyncMessage() {
  unsigned long pctime;
  const unsigned long DEFAULT_TIME = 1357041600; // Jan 1 2013

  if(Serial.find(TIME_HEADER)) {
     pctime = Serial.parseInt();
     if( pctime >= DEFAULT_TIME) { // check the integer is a valid time (greater than Jan 1 2013)
       setTime(pctime); // Sync Arduino clock to the time received on the serial port
     }
  }
}

time_t requestSync()
{
  Serial.write(TIME_REQUEST); 
  return 0; // the time will be sent later in response to serial mesg
}

void loop(){   
  if (Serial.available()) {
    processSyncMessage();
  }
  if (timeStatus()!= timeNotSet) {
    digitalClockDisplay(); 
  }
  if (timeStatus() == timeSet) {
    digitalWrite(13, HIGH); // LED on if synced
  } else {
    digitalWrite(13, LOW);  // LED off if needs refresh
  }
  delay(1000);
 
  time_t t = now(); // Store the current time in time
                    //  variable t
                   
  hour(t);          // Returns the hour for the given
                    //  time t
  minute(t);        // Returns the minute for the given
                    //  time t
  second(t);        // Returns the second for the given
                    //  time t
  day(t);           // The day for the given time t

  weekday(t);       // Day of the week for the given
                    //  time t 
  month(t);         // The month for the given time t

  year(t);          // The year for the given time t
 
 

  Serial.print(year(t));
  Serial.print("/");
  Serial.print(month(t));
  Serial.print("/");
  Serial.print(day(t));
  Serial.print(" ");

  Serial.print(hour(t));
  printDigits(minute(t));
  printDigits(second(t));
  Serial.println("");
}



I am using the tab class TIME.H


Thanks!!!!!!!
regards,

Pedro, from Portugal!!!!!
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: calim on Aug 29, 2013, 03:26 pm
Hello,

I'm currently working on a sketch witch will use several (may be 9+) changeable repeated alarms and I'm expecting difficulties with my ram usage (Arduino Nano v3).
As I understand, I can get the alarm id by "AlarmId   myTimer = Alarm.alarmRepeat(15, 00, 00, Repeats); " and delete the alarm by "Alarm.free(id);" if I want to set a new alarm.

Is there also a way to read the current alarm values?

This way I could save the currently used variables for hour and minute of each alarm so I can display them on lcd each time I want to change the alarm time.

Thanks
calim

edit: The timers do not seem to work at all. I checked using serial.print in all funktions of the sketch. I use three "Alarm.timerRepeat(10, Function);" in the setup-section and two "Alarm.timerOnce" in the sketch right now and the functions never start. I used only alarm.delay delays in the sketch. ->???
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: nickgammon on Oct 10, 2013, 12:34 pm
Recent posts about the DS1302 moved to http://forum.arduino.cc//index.php?topic=192580.0
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: ladinek on Oct 29, 2013, 04:00 pm
I am working with DS1307, and I noticed that if the module is not connected, the library return time value instead of reporting error. I think this should be corrected. I noticed this with weak battery in the DS1307 module, then I played with disconnecting module at all. I am programmer and am able to correct this bug myself, but I think better way is 1) not having modified versions of "standard" libraries and 2) fixing this would be good for entire community. Several ways of fixing is for example: Check device on the I2C bus, writing some "magic" bytes when setting time to the DS1307 memory and then checking them, and most paranoid, perhaps checking all bits in the time information which _should_ be 0, if they really _are_ 0.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mem on Oct 29, 2013, 04:57 pm
Hi ladinek,

I would be happy to add this feature to the library after it is well tested with the various chips compatible  with DS1307 that the library currently works with.
I suggest you create a new thread for your DS1307 enhancements when you are ready to post some code, and add a link to that thread here.

Michael Margolis
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Erdelyisebestyen on Oct 30, 2013, 06:56 pm
Hi,

Thanks a lot, I had the same problem. It seems to be proper solution.

Thanks again
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: ladinek on Oct 31, 2013, 04:23 pm
One more question, I have noticed you declare member functions of the DS1307 class as _static_, I tried to add one private variable and had problems compiling. So I googled a lot, and static class member function is not the same as the static function in "classic" C. It has something to do with "this". In other libraries member function are not declared as static. Can you explain reasons for this?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: nickgammon on Oct 31, 2013, 08:35 pm
Static class variables do not "belong" to instances of the class but the class itself. Typically you might use a static variable to count how many class members have been instantiated.

Quote

I tried to add one private variable and had problems compiling.


Perhaps show the code and the error.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: ladinek on Nov 03, 2013, 10:14 am
In the class definition in DS1307RTC.h I added variable present:
Code: [Select]
  private:
static uint8_t dec2bcd(uint8_t num);
    static uint8_t bcd2dec(uint8_t num);
uint8_t present;

Then in constructor I try to access this variable:
Code: [Select]
DS1307RTC::DS1307RTC()
{
  Wire.begin();
  Wire.beginTransmission(DS1307_CTRL_ID);
  Wire.write((uint8_t)0x00);
  if (Wire.endTransmission() == 0) present = 1;
  else present = 0;
}

Attemting to compile, I get errors like this:
Code: [Select]
D:\arduino-1.0.5\libraries\DS1307RTC/DS1307RTC.cpp:35: undefined reference to `DS1307RTC::present'
I tried declare variable present as either static or not, same result.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: nickgammon on Nov 03, 2013, 10:29 am
Now show all the code so I can reproduce it.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: ladinek on Nov 03, 2013, 01:48 pm
I solved it. Problem is, that you cannot access non-static member variable from static function. What I tried to do is add member variable present, which is true or false depending of success in communication with module. And if you declare static member variable, you must alse _define_ it, so I added
Code: [Select]
uint8_t DS1307RTC::present = 0;
just before contructor of the RTC object at the end of ds1307rtc.cpp.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: ladinek on Nov 03, 2013, 01:59 pm
Here is my modification of the library. I added member flag present, and set its value to true (1) or false (0) depending on success or failure in communication with the hardware. I modified the library as little as possible, you can compare my modification with original version. I modified only the read access to hardware. The RTC.get() function returns 0 (i.e. 1.1.1970) if the hardware is not present. It even correctly set timeStatus, if you for instance connect the DS1307 and then disconnect it, time continues to run, but the variable is set to timeNeedsSync after sync interval expires.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: nickgammon on Nov 04, 2013, 12:53 am

I solved it. Problem is, that you cannot access non-static member variable from static function.


Of course. Non-static variables belong to each instance, but a static function belongs to the class (not an instance).
Title: Two helper functions for getting the time from the Internet
Post by: fpoto on Dec 02, 2013, 10:37 pm
I wrote two simple functions for getting the time from the Internet.

The first one is an NTP date function (http://playground.arduino.cc//Code/NTPclient). Unlike the NTP functions I have seen out there, this one does not require allocating either a transmit or a receive buffer, neither statically nor on the stack. It does not require any ancillary library either.

The second one is  an HTTP date function (http://playground.arduino.cc//Code/Webclient). This one builds on a simple concept: just make an invalid HTTP 1.1 request to a web server out there, and parse its answer looking for the Date: header. This function is very small too and has the advantage of requiring very little code and memory space if you already use the EthernetClient or WiFiClient class in your sketch.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: russo_mic on Dec 12, 2013, 02:13 am
Hi everybody, I could use some help with TimeAlarms.

I'm building a clock that uses a GPS Shield to constantly reset the time through the setTime() function in the arduino main loop, like this:

 if (age < 500) {
       // set the Time to the latest GPS reading
       setTime(Hour, Minute, Second, Day, Month, Year);
       adjustTime(offset * SECS_PER_HOUR);

This is to ensure that GPS data isn't stale, and that the clock's time is always getting updated by gps.  the age is a function of the TinyGPS++ library.

This is unlike most examples that I've seen that uses setTime() once in the setup of the sketch.  I'm trying to set alarms through timeAlarms library and cannot get any alarms to trigger.  I've got a feeling it is because I'm using setTime() in my loop as opposed to setup.  

Could anybody shed some light on what is going on?  Thanks in advance.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Dec 12, 2013, 01:10 pm
Quote
This is to ensure that GPS data isn't stale,

Resetting what time the Arduino thinks it is will have no impact on the time that the GPS knows that it is, and will have no impact on the freshness (or staleness) of the GPS data.

Quote
I've got a feeling it is because I'm using setTime() in my loop as opposed to setup. 

Perhaps you should consider printing age. It looks to me like you are resetting the time FAR more often than you need to. If something does happen, and you get an old reading, you don't reset the time. And that makes no sense.

I think that the real problem is that you are trying to address the wrong issue.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: russo_mic on Dec 14, 2013, 04:23 am
Thanks for the reply.  However, I already thought of this, and did an experiment and had it check only every 10 minutes, and still no alarms would trigger.   The only time my alarms trigger is if setTime() is in my setup. 

This is the way I made the clock portion of the code because in the GPS example in Time library this is how it is done.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Dec 14, 2013, 02:54 pm
Quote
The only time my alarms trigger is if setTime() is in my setup. 

Do you mean that the only way that the alarms trigger is if they are defined after the time is set? If so, you'll need to re-define when the alarms should happen each time you set the time.

I still think that your approach to determining when to reset the time is fundamentally flawed.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: tao13 on Dec 31, 2013, 07:17 pm
Hello all and HAPPY NEW YEAR!

I have a problem with time library (or maybe i can not find the correct solution) if i can tell like this.
I use next code:

void setup()
{
setSyncProvider(RTC.get);  // it set clock with 12:19:43-5/10/2010 but the real value setted by me is (20,21,0,31,12,13);
}

in loop function i set the time with real time and date
example : setTime(20,21,0,31,12,13);

if i restart (don't power on/off) arduino the rtc works fine with setted values
if i restart the arduino  the clock it set up again from setSyncProvider(RTC.get) to a bad value 12:19:43-5/10/2010
what happend?

if i don't use setSyncProvider(RTC.get) i don't have value for time and date
can i use other function or not for read after restart (power of / on)  the values of rtc who i setted in it manualy?

MANY THANKS TO ALL!
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Dec 31, 2013, 11:16 pm
Code: [Select]
setSyncProvider(RTC.get);  // it set clock with 12:19:43-5/10/2010 but the real value setted by me is (20,21,0,31,12,13);
The code does NOT do what the comment says. Not even close.

Quote
if i restart the arduino  the clock it set up again from setSyncProvider(RTC.get) to a bad value 12:19:43-5/10/2010
what happend?

You have a completely incorrect understanding of what setSyncProvider() is doing. All it does is register a function to call when the time that the Arduino understands needs to be synced with the time from another source. It does NOT set the time of the external source.

Quote
if i don't use setSyncProvider(RTC.get) i don't have value for time and date

You would if you called RTC.get() yourself.

Quote
can i use other function or not for read after restart (power of / on)  the values of rtc who i setted in it manualy?


You could post all of your code. The only thing wrong with your snippet is the comment. Therefore, the problem MUST be in code you didn't bother to post.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: tao13 on Jan 01, 2014, 10:44 am
Many thanks for your answer.

I understand now.
I use for set rtc
rtc.write(tm);
and for read
rtc.read(tm).

I understand that rtc time is different what is set for time/timealarm with setime(....).

If I want to use the alarm I must put this in code?

loop()
{
  rtc.read(tm);
  setTime( "this parse rtc values ");
}

must I put in setup:
setSyncProvider(rtc.get()); ???

Many thanks again for all of your support.
HAPPY NEW YEAR.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Jan 01, 2014, 02:30 pm
Where in that second code have you connected the Time library to the time that the RTC returned? If you have an RTC, why is it necessary to use the Time library?

All of the Time functions (hour(), minute(), second(), etc.) call now(), which determines whether the function defined by the setSyncProvider() call needs to be called to update the Time library's idea of what time it is.

Since your second code does not call setSyncProvider, now() has no way of knowing what time it really is, despite there being a RTC that it could get the time from.

You would need to use setTime(RTC.get()) to tell the Time library what time the RTC thinks it is.

But, before you bother with that, you need to make sure that your RTC is working. There were examples that came with your RTC that you should be using to verify that the RTC IS functioning.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: tao13 on Jan 01, 2014, 07:43 pm
Hi and thanks again.
Yes , I have a rtc ds1307 module.
I read the rtc time and it is ok works fine.
I need to use alarm function from timealarm library so like you said
in setup function I must put :
setTime(RTC.get()) without any setSyncProvider
is it right?

another question , if I put want to use one of next functions (web page push a button and define one of them)
Alarm.alarmRepeat
Alarm.timerRepeat
Alarm.timerOnce
I have how delete/deselect/unrun them in one moment without reset arduino?

Many thanks again for your support
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Jan 01, 2014, 10:10 pm
Quote
in setup function I must put :
setTime(RTC.get()) without any setSyncProvider
is it right?

You can use the setTime(RTC.get()); call if you are not interested in having the Arduino access the RTC periodically. The Arduino is a lousy time keeper, over any length of time. Having it access an accurate time keeper, like the RTC, periodically is generally a good idea.

The setSyncProvider() function is how you tell the Arduino to get a new time from the accurate source. That is, it is how you tell the Time class what function to call to get a new time.

Quote
if I put want to use one of next functions (web page push a button and define one of them)

A web page can't push a button. A web page can display a button. The user can press the button, which will cause the browser displaying the page to make a new GET request of the server that served the original page (usually, the request is to the same server, though, in theory, it doesn't need to be). The server then interprets the new GET request, and sees that it needs to do something, based on the added information in the GET request.

Are you planning on having the Arduino wear an ethernet shield, and be a server?

Quote
I have how delete/deselect/unrun them in one moment without reset arduino?

I don't understand this question. The functions listed return the ID of the alarm that is set. You can store that ID, and later remove the alarm, reset the alarm, etc.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: larryd on Jan 01, 2014, 11:07 pm
Quote
The setSyncProvider() function is how you tell the Arduino to get a new time from the accurate source. That is, it is how you tell the Time class what function to call to get a new time.

As Pauls says.
Add this line to the setup() function:
    setSyncProvider(RTC.get);    //Use the RTC to synchronize the Arduinop clock.   Use the RTC.get() function  to do this.

Also you can add this line, however it does default to 300 seconds if you don't:
    setSyncInterval(600);           //Sync the clock every 600 seconds (10 minutes)
                                                     //So, every 10 minutes the Arduino clock is set to what is in the external RTC.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: tao13 on Jan 02, 2014, 08:21 pm
Hi all and many thanks for your answers.

I understand now and it works fine.
I use an rtc and arduino mega and Ethernet shield.
I know  about" push button" but my English is not very good and maybe I can explain very well.
The button works and send a command and parse it and setime.
Understood setSyncProvider now.

All are cleare now without one thing : disarm an alarm
if I have an alarm set in setup or whatever
in one moment I need to delete it / remove it from memory or loop function , rest it
what function I can use.
example:
in setup I set Alarm.alarmRepeat( time , functionname)
and after a time in loop I need to disabled alarm who setted in setup
how I do this.

thanks again for all of your support.


Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: larryd on Jan 04, 2014, 03:12 am
Quote
and after a time in loop I need to disabled alarm who setted in setup
how I do this.

I don't know any way of deleting it and then recovering the memory (RAM) it uses, but if you want to disable
the alarm function that it Calls you might try the following idea:
Code: (NOT TESTED) [Select]

void setup()
{
  Alarm.alarmRepeat(11,00,0, AlarmAMpills);   
  //Other stuff
}

void loop()
{
  //do stuff

  if (a_condition == true)
  {
    disabled = true;
  }
}

//========================================== 
  void AlarmAMpills()
{
  if (disabled == true)
    {
    return;  // don't take any further action since this function is disabled
    }
  Serial.print("Take your morning pills");
  // Process some more stuff as needed

}
//==========================================
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: tao13 on Jan 04, 2014, 05:13 pm
Thanks for your idea but it doesn't remove or disabled alarm from memory.
it is o way with ALARMID but it doesn;'t support very much alarm.
I need to run 70 alarms in memory (10 programs on 7 days).
Thanks.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Jan 04, 2014, 05:16 pm
Quote
I need to run 70 alarms in memory (10 programs on 7 days).

By default, the TimeAlarm class supports 6 alarms.

It's time for you to put your tap dancing shoes away. You keep saying "That didn't work" without saying what "that" is. Post your code, or solve your problem yourself.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: tao13 on Jan 07, 2014, 12:08 pm
Thanks again anyway for your answer.
I solved my problem without timealarm and time library for next reasons:
1 - Alarm.repeate doesn't work I have all libraries in my code (not trigger it)
#include <DS1307RTC.h>
#include <Wire.h>
#include <Time.h>
#include <TimeAlarms.h>

2. timealarm doesn't have a function to execute a code between 2 times/date some like
Start 20:00:00 06/jan/2014
Stop 21:10:00 07/jan/2014

Thanks again to all.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Jan 23, 2014, 01:30 pm
Quote
Is there anyway to "set" the UNIX time from a variable?

Yes. HTH.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Jan 25, 2014, 01:06 pm

How do I do that?

Write the proper code.

When you stop playing what if games, and post some code that defines the context of your question, we can actually help.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Jan 25, 2014, 03:41 pm
Quote
This is the code that gets the UNIX time.

No, it isn't. The code that MIGHT get the UNIX time is the getTime() function, which you didn't bother posting. Post ALL of your code.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: edmundssprogis on Feb 03, 2014, 05:47 pm
Hi,

If someone is using time.cpp on Arduino Mega 2560 and concerns about board running longer than 49 days without restart, then

function now() first chunk "
while( millis() - prevMillis >= 1000){     
    sysTime++;
    prevMillis += 1000;   
"
needs to be replaced with this chunk "
unsigned long currtime = millis();   
   if (currtime > prevMillis)   // if timer has not run over max value
   {
      if (currtime - prevMillis >= 1000) // if the second has passed
      {
         sysTime++;
         prevMillis = currtime;
      }
   }
   else   // if timer has rolled over
   {
      if ((0xFFFFFFFF - prevMillis + currtime) >= 1000)
      {
         sysTime++;   
         prevMillis = currtime;
      }
   }
"

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: JChristensen on Feb 04, 2014, 12:16 am

If someone is using time.cpp on Arduino Mega 2560 and concerns about board running longer than 49 days without restart,


No one should be concerned in the slightest, there is absolutely no issue running the Time library for arbitrarily long periods. I didn't read your code, but whatever it is, it's totally unnecessary.

PS: Unless you're planning to be around in 2038 (http://en.wikipedia.org/wiki/Year_2038_problem).
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: spyking on Feb 14, 2014, 08:46 pm
Hi!

I am trying to have certain events occur during the day, and certain during the night. I have got that figured out, but need some pointers on how to check on initial start up if it's day or night.
This is my current approach.

Code: [Select]

// Alarm times
//Day
int dhh = 6;
int dmm = 30;
int dss = 0;
time_t Day_time = AlarmHMS(dhh,dmm,dss);


// Night
int nhh = 18;
int nmm = 30;
int nss = 0;
time_t Night_time = AlarmHMS(nhh,nmm,nss);


I tried
Code: [Select]

// Check if it's Day
  time_t check_time = AlarmHMS(hour(),minute(),second());
  Serial.println(check_time);
  if(hour()>=dhh && minute()<=Night_time)
  {
    Day();
  }
  else
  {
    Night();
  }


But I think I am going wrong with my understanding of the AlarmHMS() function.
How should I go about this?







Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: larryd on Feb 14, 2014, 10:12 pm
Just one comment, why are you not using the Time and TimeAlarms libraries?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: spyking on Feb 14, 2014, 10:23 pm
If that was addressed to me, I am using the libraries to trigger the alarms once per day.

But on initial power up, I need to check based on the alarm times, if the state should be on or off.

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Feb 14, 2014, 11:17 pm
Quote
But on initial power up, I need to check based on the alarm times, if the state should be on or off.

My crystal ball is saying line 27 of WeirdStuff.java needs to be fixed. I can't see how that could possibly be true, so you probably need to post your code.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: spyking on Feb 15, 2014, 11:13 am
Hahah! My bad!

Here is the setup() snippet.
I tried a new approach, but It's not perfect.
Code: [Select]

#include <Time.h>
#include <Wire.h>
#include <DS1307RTC.h>
#include <TimeAlarms.h>
#include <LiquidCrystal.h>

LiquidCrystal lcd(8, 9, 10, 11, 12, 13);

boolean daytime;

// RelayPins
int LightRelay_1 = 2;
int LightRelay_2 = 3;
int PumpRelay = 4;

// Alarm times
tmElements_t dtm,ntm;

void setup()
{
  Serial.begin(9600);
  lcd.begin(16, 2);
  setSyncProvider(RTC.get);   // the function to get the time from the RTC
  if(timeStatus()!= timeSet)
    Serial.println("Unable to sync with the RTC");
  else
    Serial.println("RTC has set the system time");     

  // Set output mode
  pinMode(LightRelay_1, OUTPUT);   
  pinMode(LightRelay_2, OUTPUT); 
  pinMode(PumpRelay, OUTPUT); 
  //Day
  dtm.Hour = 6;
  dtm.Minute = 30;
  dtm.Second = 0;
  dtm.Day = day();
  dtm.Month = month();
  dtm.Year = year()-1970;
  time_t day_time = makeTime(dtm);
  Serial.println (day_time);

  // Night
  ntm.Hour = 18;
  ntm.Minute = 30;
  ntm.Second = 0;
  ntm.Day = day();
  ntm.Month = month();
  ntm.Year = year()-1970;
  time_t night_time = makeTime(ntm);
  Serial.println(night_time);


  // Set up Alarms
  Alarm.alarmRepeat(dtm.Hour,dtm.Minute,dtm.Second, Day);
  Alarm.alarmRepeat(ntm.Hour,ntm.Minute,ntm.Second, Night);

  // Check if it's Day
  time_t check_time = now();
  Serial.println(check_time);
  if(check_time>=day_time && check_time<=night_time)
  {
    Day();
  }
  else
  {
    Night();
   }
}
void loop()
{//Display stuff removed
}
void Day()
{
Serial.println("Day");
}
void Night()
{
Serial.println("Night");
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Feb 15, 2014, 02:45 pm
Quote
I tried a new approach, but It's not perfect.

The code does something. You have not said what it does.
You want it to do something. You have not said how that differs from what it actually does.

Your response wasn't perfect, either, and now you know why. To bad we still don't know what your problem is.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: spyking on Feb 15, 2014, 06:43 pm

Quote
I tried a new approach, but It's not perfect.

The code does something. You have not said what it does.
You want it to do something. You have not said how that differs from what it actually does.

Your response wasn't perfect, either, and now you know why. To bad we still don't know what your problem is.


I am trying to have certain events trigger during the day, and certain events trigger during the night.

On initial stat up, I need to determine if it's night or day based on the current time.
ie. Suppose Day is set to start at 06:00 and night starts at 18:00.
On initial start up, based on the current time returned from the RTC, for example 13:00 then it should be day.

Initially I was trying to get the time_t based on the AlarmHMS() function for both the alarm times, and check it against the value of AlarmHMS() with the current hour,minute,second. But I think I wasn't implementing that correctly.

The second approach is to use maketime() to get the time elapsed for each of the alarms  and check it against now(). It works for most of the part, but not if I swap the day - night alarm times.
ie. If Day is to start at 18:00 and night begins at 6:00, then since In makeTime() I use the current day() to determine the time from 1970.

In summery,
What would be good way to determine if the current time is in between the two set alarm times?
if dayalarm_time<current_time<nightalarm_time

Hope that makes more sense now?



Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mem on Feb 16, 2014, 10:38 am
Hello spyking,

If you want to know if the current time is day or night, you could do something like the following function. In this example, day starts at 6AM and ends at 6PM:
Code: [Select]
//returns true if it is day time now
boolean isDaytimeNow()
{
  // in this example, day starts at 6AM and ends at  6 PM
  int startDayHour = 6; // 6 am
  int endDayHour = 18; // 6PM
 
  int thisHour = hour();
 
  // the following determines if the current hour is within the day start and end times
  return thisHour >= startDayHour && thisHour < endDayHour; 
}

Calling that function will return true if its day and false if its night
Here is the code extended to support to start and end times of any hour and minute:
Code: [Select]
//returns true if it is day time now
boolean isDaytimeNow()
{
  // in this example, day starts at 6:30AM and ends at  6:30 PM
  int startDayHour = 6; // 6 am
  int startDayMinute = 30;
  int endDayHour = 18; // 6PM
  int endDayMinute = 30;
 
  int thisHour = hour();
  int thisMinute = minute();
 
  // the following determines if the current hour and minute times are within
  // the day start and end times
  return thisHour >= startDayHour &&
         thisMinute >= startDayMinute &&
         thisHour < endDayHour &&
         thisMinute < endDayMinute; 
}


I guess that what you are looking to do is to set the daytime flag at at startup and then toggle this off and on using the alarms, perhaps something like this:
Code: [Select]
#include <Time.h>
#include <Wire.h>
#include <DS1307RTC.h>
#include <TimeAlarms.h>

boolean daytime;

// Alarm times
tmElements_t dtm,ntm;

void setup()
{
  setSyncProvider(RTC.get);   // the function to get the time from the RTC
  //Day
  dtm.Hour = 6;
  dtm.Minute = 30;
  dtm.Second = 0;

  // Night
  ntm.Hour = 18;
  ntm.Minute = 30;
  ntm.Second = 0;

  // Set up Alarms
  Alarm.alarmRepeat(dtm.Hour,dtm.Minute,dtm.Second, Day);
  Alarm.alarmRepeat(ntm.Hour,ntm.Minute,ntm.Second, Night);
}

void loop()
{
}

void Day()
{
  Serial.println("Day");
  daytime = true;
}

void Night()
{
  Serial.println("Night");
  daytime = false;
}

//returns true if it is day time now
boolean isDaytimeNow()

  int thisHour = hour();
  int thisMinute = minute();
 
  // the following determines if the current hour and minute times are within
  // the day start and end times
  return thisHour >=  dtm.Hour &&
         thisMinute >= dtm.Minute &&
         thisHour < ntm.Hour &&
         thisMinute < ntm.Minute; 
}

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: spyking on Feb 16, 2014, 12:27 pm


Calling that function will return true if its day and false if its night
Here is the code extended to support to start and end times of any hour and minute:
Code: [Select]
//returns true if it is day time now
boolean isDaytimeNow()
{
  // in this example, day starts at 6:30AM and ends at  6:30 PM
  int startDayHour = 6; // 6 am
  int startDayMinute = 30;
  int endDayHour = 18; // 6PM
  int endDayMinute = 30;
 
  int thisHour = hour();
  int thisMinute = minute();
 
  // the following determines if the current hour and minute times are within
  // the day start and end times
  return thisHour >= startDayHour &&
         thisMinute >= startDayMinute &&
         thisHour < endDayHour &&
         thisMinute < endDayMinute; 
}



This is how I initially started out, but what would happen if the the current hour is lesser than the day start, but the minute isn't?
ie.
day start hour = 6
day start minute = 30
current time  = 12:20
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mem on Feb 16, 2014, 01:18 pm
Good point!

try something like this:
Code: [Select]
boolean isDaytimeNow()
{
 // in this example, day starts at 6:30AM and ends at  6:30 PM
 int startDayHour = 6; // 6 am
 int startDayMinute = 30;
 int endDayHour = 18; // 6PM
 int endDayMinute = 30;

 int thisHour = hour();
 int thisMinute = minute();

 boolean result = false;

 // the following determines if the current hour and minute times are within
 // the day start and end times
 if( thisHour >= startDayHour) {
   if( thisHour == startDayHour){
     result = thisMinute >=  startDayMinute;
   }
   else{
     if( (thisHour < endDayHour) || (thisHour == endDayHour && thisMinute < endDayMinute) ){
       result = true;
     }
   }                
 }
 return result;
}


like my previous post, this is untested but hopefully will get you going in the right direction

Edit: changed  test for minutes from:
    thisMinute >  startDayMinute
to
     thisMinute >=  startDayMinute;  // test for greater than or equal to
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mem on Feb 16, 2014, 01:48 pm
here is another approach to determining if its day or night:

Code: [Select]
time_t startOfDay;
time_t startOfNight;

void setup()
{
  startOfDay = timeToSeconds(6,30,0); // Hour,Min,Secs for start of day
  startOfNight = timeToSeconds(18,30,0); // Hour,Min,Secs for start of Night
}

boolean isDaytimeNow()
{
    time_t t = timeToSeconds(hour(), minute(), second());
    return (t >= startOfDay && t < startOfNight);     
}

time_t timeToSeconds(time_t H, time_t M, time_t S)
{
return (H * SECS_PER_HOUR) + (M * SECS_PER_MIN) + S;
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: spyking on Feb 16, 2014, 02:04 pm

Good point!

try something like this:
Code: [Select]
boolean isDaytimeNow()
{
  // in this example, day starts at 6:30AM and ends at  6:30 PM
  int startDayHour = 6; // 6 am
  int startDayMinute = 30;
  int endDayHour = 18; // 6PM
  int endDayMinute = 30;

  int thisHour = hour();
  int thisMinute = minute();

  boolean result = false;

  // the following determines if the current hour and minute times are within
  // the day start and end times
  if( thisHour >= startDayHour) {
    if( thisHour == startDayHour){
      result = thisMinute >  startDayMinute;
    }
    else{
      if( (thisHour < endDayHour) || (thisHour == endDayHour && thisMinute < endDayMinute) ){
        result = true;
      }
    }                 
  }
  return result;
}


like my previous post, this is untested but hopefully will get you going in the right direction


Neat! Will test it out when I get home.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mem on Feb 16, 2014, 02:13 pm
Note that I updated to posted code  to  so the minute tests for greater than or equal to the day start minute.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: SFO_user on Feb 24, 2014, 03:50 pm
I finally managed to get the TimerAlarm work for me.

Here is the code snippet from my setup function:
Alarm.alarmRepeat (13,31,0, OneThirtyPmEveryDay);
Alarm.timerRepeat (2, RepeatEveryTwoSeconds);

I have currently hard-coded the alarm Time. I would like to provide an LCD interface that will allow the user to change the time.
My concern is every time the user sets a different time, a call to alarmRepeat will create a new alarm. How can I reuse the existing alarm and update the changed time alone. I didn't see any function that allows me to change the time.
The option is to disable the Alarm on the current time, and create another Alarm but I'm afraid that I will needlessly waste memory as the Alarm on the old time is no longer useful but is sitting there occupying memory.
Can you help?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Feb 24, 2014, 04:08 pm
Look at the alarmRepeat() and timerRepeat() methods. They return values that you might not want to discard.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: tevko on Mar 05, 2014, 12:00 pm
Hi,
Thanks for the nice library! I made some changes to it (the callback parameter), so keep that in mind when reading this---I may have broken something there.

I'm having trouble with rewriting my alarms. I'm switching on 12 lamps with separate timers. Here's a snippet of my code (inside loop()):

Code: [Select]
   
} else if (command == MESSAGE_TIMER_ON) {
     int floors=message[0];
     int lamps=message[1];
     int h=message[2];
     int mi=message[3];
     int sec=message[4];
     char msg;
     if (tons[floors][lamps]==0) {
       theOnTimers[floors][lamps]=Alarm.alarmRepeat(h,mi,sec,&alarm_cb,&theOnAlarms[floors][lamps]);
       tons[floors][lamps]=1;
       msg=0x03;
       writeMessage(MESSAGE_OK,&msg,1);
     } else {
       Alarm.write(theOnTimers[floors][lamps],AlarmHMS(h,mi,sec));
       msg=0x04;
       writeMessage(MESSAGE_OK,&msg,1);
     }
   }


The first time my program reaches this point (for each lamp), everything works nicely: Alarm.alarmRepeat is used and timer works as intended (light switches on). The following times the correct code block gets called (determined from the response message 0x04), but the timer does not turn the light on.

Am I missing something obvious? Should I re-enable the alarm after Alarm.write? I'll go re-check my changes to the library if there's nothing obviously wrong in this block of my code.

Thanks for any comments,
Tevko

edit:
The id variable is set up as
Code: [Select]

AlarmID_t theOnTimers[3][4];

And is not tampered with anywhere else.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mem on Mar 05, 2014, 03:42 pm

I'm having trouble with rewriting my alarms. I'm switching on 12 lamps with separate timers ...



One thing you can try  is to replace the Alarm.write with a call to Alarm.free with the ID you want to change and then call Alarm.create with the new time.  Alarm.write sets the alarm time and activates the alarm but it does not update the scheduler.

Otherwise, there is a lot going on there and It's difficult to see exactly what is happening with the alarms. Can you create a simple test sketch that just handles the alarm rescheduling and see if that works as expected.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: tevko on Mar 05, 2014, 04:58 pm
Thanks for the response mem!


One thing you can try  is to replace the Alarm.write with a call to Alarm.free with the ID you want to change and then call Alarm.create with the new time.


That's a good idea, I'll try with Alarm.free, or I'll first try to call Alarm.enable to see if it helps.



Can you create a simple test sketch that just handles the alarm rescheduling and see if that works as expected.


I'll do that if I can't find a solution to this problem with Alarm.free.

edit:
Alarm.free+Alarm.create did just what I wanted, thanks your help! I'll see if I can find out why Alarm.write was not enough for this.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: samly_dixon on Mar 15, 2014, 06:00 am
Hello Mem,

I am building a Hour Counter for my Air Compressor which works eventually. I need to keep a track on the running time in order to do a proper service.
I have the RTC module and it works fine with Time.h. I have developed the program upto some level which gives the elapsed time after 5 sec delay (That is 5 Sec) . but when I tried to do the same subtraction with a if condition corresponding to a button switch it gives 0 duration.

Can you please help me to over come this.

Code: [Select]
/*
* TimeRTC.pde
* example code illustrating Time library with Real Time Clock.
*
*/

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

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int se;
int minu;
int hr;
const int buttonPin = 8;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status


void setup()  {
  Serial.begin(9600);
  lcd.begin(20, 4);
    // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);     
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);     
 
  setSyncProvider(RTC.get);   // the function to get the time from the RTC
  if(timeStatus()!= timeSet)
     lcd.println("Unable to");
  else
     lcd.println("RTC has set");     
}

void loop()
{
  int timse1;
  int timse2;
  int durse;
  int timmin1;
  int timmin2;
  int durmin;
  int timhr1;
  int timhr2;
  int durhr;
 
  int timsev1;
  int timsev2;
  int timminv1;
  int timminv2;
  int timhrv1;
  int timhrv2;

    buttonState = digitalRead(buttonPin);
   //setTime(12,44,0,3,6,14);
  digitalClockDisplay(); 
   delay(1000);
   lcd.clear();

// check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {     
    // turn LED on:   
    digitalWrite(ledPin, HIGH); 
   
  timsev1= getse();
  timminv1= getminu();
  timhrv1= gethr();
  lcd.print("ON");
 
// 
//  if (buttonState == LOW){
// 
// 
//   digitalWrite(ledPin, LOW);
//    timsev2 = getse();
//    timminv2 = getminu();
//    timhrv2 = gethr();
//    lcd.print("OFF");
// 
//  }
  }
  else {
    // turn LED off:
    digitalWrite(ledPin, LOW);
    timsev2 = getse();
    timminv2 = getminu();
    timhrv2 = gethr();
    lcd.print("OFF");
  }

 
  lcd.print(timse1);

durse = timse2-timse1;
durmin = timmin2-timmin1;
durhr = timhr2-timhr1;

lcd.setCursor(1, 2);
lcd.print(durhr);
lcd.print(':');
lcd.print(durmin);
lcd.print(':');
lcd.print(durse);

delay(1000);

}

int getse(){
    time_t t= now();
  se = second(t);
 
  return se;
}

int getminu(){
    time_t t= now();
  minu = minute(t);

  return minu;
 
}

int gethr(){
  time_t t= now();
  hr = hour(t);
  return hr; 
}


void digitalClockDisplay(){
  // digital clock display of the time
  lcd.print(hour());
  printDigits(minute());
  printDigits(second());
 
  /*Serial.print(" ");
  Serial.print(day());
  Serial.print(" ");
  Serial.print(month());
  Serial.print(" ");
  Serial.print(year());
  Serial.println(); */
}


/*int duration (int ms, int mp){
  //function to find the varience b/w start time n stop time
  int hd;
  int md;
 
// hd= hp-hs;
  md= mp-ms;
 
  //lcd.print(hd);
  printDigits(md);
}
*/


 



void printDigits(int digits){
  // utility function for digital clock display: prints preceding colon and leading 0
  lcd.print(":");
  if(digits < 10)
    lcd.print('0');
  lcd.print(digits);
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mem on Mar 15, 2014, 08:38 am
Hi Samly_dixon, Its not clear on what you want to do and I did not see the code that you are trying to get working. Can you say more about exactly what you want to test with the if statement when a button is pressed.
I noticed that you have created functions to return the current hours, minutes and seconds. These functions already exist as follows:   seconds(), minutes() , hours().
You have a function named duration that has the following comment:
   //function to find the variance b/w start time n stop time
But it is not clear which argument is the start time and which is the stop time. It would be clearer if you used descriptive names for your variables instead of: ms, mp,hd, md etc.

To find the difference between two times, use the time_t returned from the now()function. For example:
Code: [Select]
time_t event = now();
// … some time later
long duration = now() - event; // the duration since the event in seconds

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: arcQuisumbing on Mar 16, 2014, 09:57 am
Good day all.

Please pardon me with this noob question/request.

I am trying this Time libraries with the samples but I'm always getting the 'time_t' does not name a type and 'set_Time' was not declared in this scope errors while compiling.  Please note that I am not much into programming, however, if given a flawless sample, I think I can work through the codes and modify them to achieve what I need.

Here's my task.

Similar to the Alarm sample, I wanted to program my arduino micro paired with a 4-channel relay module to switch 4 different lights, the television and the radio at specific times of the day but differs on each day of the week.  I had a previous project that I might be able to use for the television and radio On-Off by Infrared remote control.  So all I need is to make the time and alarm work without any other hardware attached.

Could anyone please point me to the right direction as I have around 10 days to complete this project.  I am bound to go for a vacation and hoping that with this project, I can keep my house safe from breaking and entering which happened last year.

Providing me with a code to start with will be even better.

Your help will be highly appreciated.

More power to you all.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Mar 16, 2014, 10:16 am
Quote
Providing me with a code to start with will be even better.

You clearly already have code that you haven't posted.

You also haven't mentioned which version of the IDE you are using, or which version of the Time library (as in where you got it).
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: samly_dixon on Mar 16, 2014, 06:51 pm

Hi Samly_dixon, Its not clear on what you want to do and I did not see the code that you are trying to get working. Can you say more about exactly what you want to test



Mem,
Sorry for being unclear on what I want to test. Basically I want to count the durations of the running machine.

Our machine works every 15 minutes will work for 5 minutes. But it is not constant. It changes due to the usage. So I am developing a system to count the exact running time of the machine. like, how many minutes actually the machine operates.

so when the machine is in the work for one day I must be able to see how many hours the machine has been run actually..





Code: [Select]
time_t event = now();
// … some time later
long duration = now() - event; // the duration since the event in seconds





Thanks alot for this simple and beautiful idea. It works. Now I have to merge this duration coding with condition. When the machine is starting I have to call a event = now(); and when the machine goes off I need to call duration = now() - event;

Hope my merging will work,

Basically I am a beginner to arduino. It has been a interesting process for me,
Can you tell me how can I get the duration between a button switch on and off.?
Special thanks for your quick response.

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mem on Mar 16, 2014, 07:15 pm

Basically I am a beginner to arduino. It has been a interesting process for me,
Can you tell me how can I get the duration between a button switch on and off.?
Special thanks for your quick response.


There are many ways to do this but if an Arduino pin can monitor the state of the machine then one approach is to capture the time of the event of a pin going high or low using the code posted earlier. Subtracting the time between these events gives you the on and off times. Accumulating the on time and off times should give you the information that you need.

I suggest you experiment with a simple sketch that reads an input connected to a switch and totals the times between the high and low transitions and prints the current switch state, time since previous change of switch state, and total accumulated times in each state to the serial port. 
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: samly_dixon on Mar 17, 2014, 10:27 am

There are many ways to do this but if an Arduino pin can monitor the state of the machine then one approach is to capture the time of the event of a pin going high or low using the code posted earlier. Subtracting the time between these events gives you the on and off times. Accumulating the on time and off times should give you the information that you need.

I suggest you experiment with a simple sketch that reads an input connected to a switch and totals the times between the high and low transitions and prints the current switch state, time since previous change of switch state, and total accumulated times in each state to the serial port. 




Hi Mem,

Thanks for your valuable tips,

I tried some thing like this.. but on my lcd display i recieve only the current time and a "on"  when  the switch is not pressed it shows current time then after 1s delay a "on".
when i press the button switch for some times the current time stays on the display untill i release the switch. it doesnt changes the display to "on" when the switch is not pressed. when i release the switch old routine comes back.

i couldnt get the duration.

Pls give me your valuable suggestion....

Code: [Select]




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

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int tim;
int lastState;

const int buttonPin = 8;     // the number of the pushbutton pin
const int ledPin =  13;
int buttonState = 0;   

void setup()  {
  Serial.begin(9600);
  lcd.begin(20, 4);
 
  setSyncProvider(RTC.get);   // the function to get the time from the RTC
  if(timeStatus()!= timeSet)
     lcd.println("Unable to");
  else
     lcd.println("RTC has set");     
}


void loop()
{
  time_t event;
   buttonState = digitalRead(buttonPin);
   //setTime(12,44,0,3,6,14);
  digitalClockDisplay(); 
   delay(1000);
   lcd.clear();
   
   if (digitalRead(buttonState) ==HIGH && buttonState == LOW ) {
     
     digitalWrite(ledPin, HIGH); 
  time_t event = now();
lcd.print("On");
   delay(1000);
   lcd.clear();
   buttonState=digitalRead(buttonState);
   }
   
   if (digitalRead(buttonState) ==LOW && buttonState == HIGH){
     
     
     digitalWrite(ledPin, LOW);
     // … some time later
long duration = now()- event; // the duration since the event in seconds

lcd.println("off");
delay(1000);
lcd.println(duration);

delay(2000);

   }



}


void digitalClockDisplay(){
  // digital clock display of the time
  lcd.print(hour());
  printDigits(minute());
  printDigits(second());
 
}


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

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: samly_dixon on Mar 17, 2014, 10:51 am
and for the information,

With that configuration LED is always on.

Samly.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: arcQuisumbing on Mar 17, 2014, 11:05 am

You clearly already have code that you haven't posted.

You also haven't mentioned which version of the IDE you are using, or which version of the Time library (as in where you got it).


Thank you for the reply Paul.

The code that I am referring to is the one included as sample with the library.

I am using 1.0.5-r2 and the Arduino Time Library is the latest one posted in the Learning/Playground page.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Mar 17, 2014, 11:15 am
Quote
The code that I am referring to is the one included as sample with the library.

Great. That narrows it down to one of 8. I'm not into guessing games.

Quote
and the Arduino Time Library is the latest one posted in the Learning/Playground page.

Post a link. There is an Update note on that page that it looks like you didn't follow.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: arcQuisumbing on Mar 17, 2014, 12:02 pm

There is an Update note on that page that it looks like you didn't follow.


Silly/Lazy me. I actually started reading the last time I visited those links but it throws me off instead educating me. I got more confused. I may just have to read again and experiment with my minimal understanding.

Otherwise, my easier solution is just to rely on the delay function of the Arduino and start the sequence at a specific time of day where my program coincides with my desired timing.  I'll just pray that no black-outs during my absence so the timing will not change.

Thanks anyway Paul.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mem on Mar 17, 2014, 02:02 pm


I tried some thing like this.. but on my lcd display i recieve only the current time and a "on"  when  the switch is not pressed it shows current time then after 1s delay a "on".
when i press the button switch for some times the current time stays on the display untill i release the switch. it doesnt changes the display to "on" when the switch is not pressed. when i release the switch old routine comes back.

i couldnt get the duration.



You are close but there are some errors in your code. You are using buttonState instead of buttonPin in your digitalRead function. Also, you have declared two event variables, one at the beginning of loop and the other in the code that handles the state where the digitalRead is high.  Move the time_t event declaration to the top of the sketch where your other global variables are declared and remove  time_t from the line where you set event= now() . You can read the arduino reference pages on declaring variables and variable scope for more on this issue.

The issues you are having are not related to the time libraries so I suggest that start a  new thread to discuss  your project and post a link here so I and others can follow.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: KennethSoh on Mar 18, 2014, 04:56 am
I'm having this problem : closing the Serial Monitor renders timeStatus()=timeNotSet.

I've tried this with HyperTerminal & I get the same behaviour : when I disconnect & then re-connect again, my UNO reports (timeStatus()==timeNotSet) to be TRUE.

Has anyone encountered the same problem? Or am I missing something here?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: samly_dixon on Mar 19, 2014, 07:53 am
Mem,



You are close but there are some errors in your code. You are using buttonState instead of buttonPin in your digitalRead function. Also, you have declared two event variables, one at the beginning of loop and the other in the code that handles the state where the digitalRead is high.  Move the time_t event declaration to the top of the sketch where your other global variables are declared and remove  time_t from the line where you set event= now() . You can read the arduino reference pages on declaring variables and variable scope for more on this issue.


Thank you so to for pointing out my silly coding errors. Its now giving the duration in seconds.  :) :) :) :)

Quote

The issues you are having are not related to the time libraries so I suggest that start a  new thread to discuss  your project and post a link here so I and others can follow.

I will open a new thread and share the link here. Thank you again for your help.

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: 5lair on May 17, 2014, 10:17 pm
I tried your solution, but I still have errors on lines 41 and 58. Here is my line replacement :

Line 48 : PGM_P  monthNames_P[] =
Line 58 : PGM_P dayNames_P[] = { dayStr0,dayStr1,dayStr2,dayStr3,dayStr4,dayStr5,dayStr6,dayStr7};
Line 59 : const char dayShortNames_P[] PROGMEM = "ErrSunMonTueWedThrFriSat";

Of course, this is not the best solution since monthNames and dayNames will be stores in RAM, but ... it works. Any better proposal is welcome !

Hope this help !

Philippe
www.lucidarme.me (http://www.lucidarme.me)

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: shrek on Jul 15, 2014, 08:35 pm
Is it possible to set the time by GSM shield instead of ethernet shield since both are in a sense connected to ntp servers.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: shrek on Jul 16, 2014, 02:30 pm
As soon as I try to verify an unmodified TimeNTP sketch I get the followiong error messages
Quote

In file included from /home/shrek/sketchbook/libraries/Time/DateStrings.cpp:11:0:
/home/shrek/sketchbook/libraries/Time/DateStrings.cpp:41:22: error: variable 'monthNames_P' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
PGM_P monthNames_P[] PROGMEM =
                      ^
/home/shrek/sketchbook/libraries/Time/DateStrings.cpp:58:20: error: variable 'dayNames_P' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
PGM_P dayNames_P[] PROGMEM = { dayStr0,dayStr1,dayStr2,dayStr3,dayStr4,dayStr5,dayStr6,dayStr7};
                    ^
/home/shrek/sketchbook/libraries/Time/DateStrings.cpp:59:24: error: variable 'dayShortNames_P' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
char dayShortNames_P[] PROGMEM = "ErrSunMonTueWedThrFriSat";


What should I do to get the time NTP request function or feature to work. Also if it can be modified to use as external source the time message provided to all gsm enabled phones by the network via the GSM shield I would appreciate it.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: sarwarislammoon on Jul 21, 2014, 08:13 pm
I am a beginner in arduino .
I just add this time library and try to test an example .
But i found those errors
/**************************************************************************/
TimeSerial.pde:12:20: warning: Time.h: No such file or directory
TimeSerial:24: error: 'time_t' does not name a type
TimeSerial.pde: In function 'void setup()':
TimeSerial:20: error: 'requestSync' was not declared in this scope
TimeSerial:20: error: 'setSyncProvider' was not declared in this scope
TimeSerial.pde: In function 'void loop()':
TimeSerial:29: error: 'timeStatus' was not declared in this scope
TimeSerial:29: error: 'timeNotSet' was not declared in this scope
TimeSerial:31: error: 'timeSet' was not declared in this scope
TimeSerial.pde: In function 'void digitalClockDisplay()':
TimeSerial:39: error: 'hour' was not declared in this scope
TimeSerial:40: error: 'minute' was not declared in this scope
TimeSerial:41: error: 'second' was not declared in this scope
TimeSerial:43: error: 'day' was not declared in this scope
TimeSerial:45: error: 'month' was not declared in this scope
TimeSerial:47: error: 'year' was not declared in this scope
TimeSerial.pde: In function 'void processSyncMessage()':
TimeSerial:65: error: 'time_t' was not declared in this scope
TimeSerial:65: error: expected `;' before 'pctime'
TimeSerial:69: error: 'pctime' was not declared in this scope
TimeSerial:72: error: 'pctime' was not declared in this scope
TimeSerial:72: error: 'setTime' was not declared in this scope
TimeSerial.pde: At global scope:
TimeSerial:77: error: 'time_t' does not name a type
/****************************************************************************/

I am using arduino uno r3
and ide version is 1.0.5

please any one help me

Thank you 


Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Lundin on Aug 09, 2014, 09:45 pm

I am a beginner in arduino .
I just add this time library and try to test an example .
But i found those errors
/**************************************************************************/
TimeSerial.pde:12:20: warning: Time.h: No such file or directory



A bit old post, but anyway
You need to download and put the Time library where you installed the IDE (like:  C:/program(x86)/Arduino/Libraries/Time  
The sketch can't find this library when you try to compile and send it to the UNO .
If you have downloaded the Time library, be sure it's not put inside a second folder by the same name ( i.e Time/Time)

Good luck
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Aug 09, 2014, 09:50 pm
It would be better to put the Time library in the correct place which is the libraries folder of the sketch folder.

Like this C:\Users\Bob\Documents\Arduino\libraries

The point about having the library folder one level too deep still stands though.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Lundin on Aug 10, 2014, 12:47 am

It would be better to put the Time library in the correct place which is the libraries folder of the sketch folder.

Like this C:\Users\Bob\Documents\Arduino\libraries

The point about having the library folder one level too deep still stands though.

oops.. sorry..didn't mean to be misleading  and i didn't know there were a library folder there too.. but it makes perfect sense now that you've mentioned it.

Thanks for pointing it out
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: FattyPatty01 on Aug 10, 2014, 01:51 am
Hey guys,

I happen to have a question about TimeAlarms. Can you use the TimeAlarm library to activate a servo motor at a certain time? And also, can you sync the RTC DS1307 to the TimeAlarm?  If you can, how do you? Any help would be appreciated. Thanks.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Aug 10, 2014, 08:07 am
Quote
i didn't know there were a library folder there too..
The libraries folder in the sketch folder is designed to hold user contributed libraries that are available to all versions of the IDE of which there may be several installed as it is upgraded.  The libraries folder under the main Arduino folder is designed to hold libraries supplied with the IDE of which there could potentially be more/different versions specific to an IDE version.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Aug 10, 2014, 08:13 am

Hey guys,

I happen to have a question about TimeAlarms. Can you use the TimeAlarm library to activate a servo motor at a certain time? And also, can you sync the RTC DS1307 to the TimeAlarm?  If you can, how do you? Any help would be appreciated. Thanks.
The answer to both of these is yes.  Look at the example with the TimeAlarms library to see how to carry out actions at specific times or to repeat them at specific intervals.  The TimeAlarms library makes use of the Time library which makes it possible to synch the alarms with an RTC.  Simply set the time using the RTC and it becomes available to TimeAlarms.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: JimboZA on Aug 10, 2014, 10:19 am
Is there a limit to the number of timers and alarms that can be set in the TimeAlarms library? I'm getting some funnies where some are not honoured, and I'm wondering if there's a limit. (I'm going to do some proper testing before I post code, but thought I'd ask if there's a known limit first. Don't shout at me for not posting code yet  :) )

edit.... the readme says 6 but that can be increased by editing  the constant dtNBR_ALARMS in the header.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Aug 10, 2014, 11:29 am
You found the answer that I was going to point you at.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: JimboZA on Aug 10, 2014, 11:34 am

You found the answer that I was going to point you at.



I had read the page on the 'net, but then I thought to my self, "self, maybe the readme has more" and I found it has a faq. I really think that faq should be on the web site!

Nice easy to use library though.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Aug 10, 2014, 12:14 pm
Quote
maybe the readme has more
I don't know what the World is coming to.
Firstly you actually look at the readme and secondly it is actually helpful !

There is some good stuff in the readme including details of the low level functions that provide access to the alarms via the alarm ID which can be useful and the FAQ section really does contain what must be FAQs
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Lundin on Aug 10, 2014, 12:38 pm
Removed my question, i found another RTC library that works not only with the DeadOn 3234, but also the LC studio SD cardreader (which were the next headache the other library didn't like).. the new foundings also works with Time/TimeAlarm libraries..

KristoZ RTC 3234 lib (https://github.com/KristoZ/Arduino_DS3234_RTC_library)

Big thumb's up for creating this library Mem.. with the headache gone and problem solved all is good.

All the best
Magnus
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Lundin on Aug 16, 2014, 10:34 am
So it happens that i'm back with a somewhat clearer mind..  What i thought worked with my previous solution, didn't actually do anything.
I sync'ed KristoZ library with the Time library with SetSyncProvider().. and as 'Time' were not sync'ed to the DeadOn RTC the time didn't reveal what the RTC were sending.

So, i'll re-thread my question about the sync errror calling SetSyncProvider() with the DS3234 RTC.
Code: [Select]

DS3234_m_trigg_2.ino:103:33: error: cannot convert 'DS3234::getTime' from type 'Time (DS3234::)()' to type 'getExternalTime {aka long unsigned int (*)()}'


Is this possible to remedy? Or is it a to big of a change in the library it's completely off the charts.

Thanks for any info about this.

EDIT: Updated the question with this header code of the DS3234
Code: [Select]

/*
  DS3234.h - Arduino library support for the DS3234 SPI Bus RTC
  Copyright (C)2014 Henning Karlsen. All right reserved
 
  This library has been made to easily interface and use the DS3234 RTC with the
  Arduino and chipKit development boards.
  This library makes use of the built-in hardware SPI port of the microcontroller
  so there are some pin connections that are required (see the manual).

  You can find the latest version of the library at
http://www.henningkarlsen.com/electronics

  If you make any modifications or improvements to the code, I would appreciate
  that you share the code with me so that I might include it in the next release.
  I can be contacted through http://www.henningkarlsen.com/electronics/contact.php

  This library is free software; you can redistribute it and/or
  modify it under the terms of the CC BY-NC-SA 3.0 license.
  Please see the included documents for further information.
*/
#ifndef DS3234_h
#define DS3234_h

#if defined(__AVR__)
#include "Arduino.h"
#include "hardware/avr/HW_AVR_defines.h"
#elif defined(__PIC32MX__)
#include "WProgram.h"
#include "hardware/pic32/HW_PIC32_defines.h"
#define F(str) (str)
#elif defined(__arm__)
#include "Arduino.h"
#include "hardware/arm/HW_ARM_defines.h"
#endif

#define FORMAT_SHORT 1
#define FORMAT_LONG 2

#define FORMAT_LITTLEENDIAN 1
#define FORMAT_BIGENDIAN 2
#define FORMAT_MIDDLEENDIAN 3

#define MONDAY 1
#define TUESDAY 2
#define WEDNESDAY 3
#define THURSDAY 4
#define FRIDAY 5
#define SATURDAY 6
#define SUNDAY 7

class Time
{
public:
uint8_t hour;
uint8_t min;
uint8_t sec;
uint8_t date;
uint8_t mon;
uint16_t year;
uint8_t dow;

Time();
};

class DS3234
{
public:
DS3234(uint8_t ss_pin);
void begin();
Time getTime();
void setTime(uint8_t hour, uint8_t min, uint8_t sec);
void setDate(uint8_t date, uint8_t mon, uint16_t year);
void setDOW(uint8_t dow);

char *getTimeStr(uint8_t format=FORMAT_LONG);
char *getDateStr(uint8_t slformat=FORMAT_LONG, uint8_t eformat=FORMAT_LITTLEENDIAN, char divider='.');
char *getDOWStr(uint8_t format=FORMAT_LONG);
char *getMonthStr(uint8_t format=FORMAT_LONG);

float getTemp();

void poke(uint8_t addr, uint8_t value);
uint8_t peek(uint8_t addr);

private:
uint8_t _ss_pin;
uint8_t _burstArray[8];

uint8_t _readByte();
void _writeByte(uint8_t value);
uint8_t _readRegister(uint8_t reg);
void _writeRegister(uint8_t reg, uint8_t value);
void _burstRead();
uint8_t _decode(uint8_t value);
uint8_t _decodeH(uint8_t value);
uint8_t _decodeY(uint8_t value);
uint8_t _encode(uint8_t vaule);

void _SPIstart(uint8_t rate = SPI_CLOCK_DEFAULT);
void _SPIwrite(byte data);
byte _SPIread(void);

};
#endif

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: kiuz on Sep 06, 2014, 10:19 am
Why don't use GitHub to collaborate on same official version? I must use this library and I want to collaborate...

#BUGS
on examples are used Serial.write(MESSAGE,BYTE) and this don't work on Arduino 1.0. ... ;
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Sep 06, 2014, 07:03 pm
Quote
Serial.write(MESSAGE,BYTE) and this don't work on Arduino 1.0. ...
That is not a bug.  it is a deliberate, documented change introduced with release 1.0

http://blog.arduino.cc/2011/10/04/arduino-1-0/
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 08, 2014, 01:26 am
Hello,
I'm having some trouble with the Alarm library.
I am using an Arduino Uno with a DS1307 module and a relay board. Basically I'm trying to set the time on my arduino from my RTC, and then have it activate two relays for a fan and lights. So I really need to have two alarms set that activate at the exact same time when the time comes.
Right now I'm having some issues as it seems that one alarm goes off , the second doesn't, I have to wait until the first one is done and then the second one kicks in. The thing is that I really need them both to work at the same time, and I can't wait for one or the other as the test delay is 90 seconds at the moment but I would like to be able to let's say set the light for 12 hours and the fan for 1 hour only. Can't have one waiting for the other...
What am I doing wrong?
Also, if you could check the way I set the time of the arduino after RTC. Basically I want this to work even thou the Arduino looses power at any point, and then comes back up continuing it's schedule. If for example the arduino is in the middle of the light alarm that can last anywhere between 10 minutes and 10 hours it looses power I want it to continue it's program. Is it possible with Alarms? Or should I look at another approach? I also have an i2c eeprom for storing the alarms and I will add a LCD with buttons.
At the moment I'm trying to find the best approach for my needs.
Thank you

edit:
And it gets more complicated if I want to have the fan start let's say 3 or 4 times a day for 5 minutes. How do I do to make sure it resumes operation after a power failure?

Code: [Select]
#include <Wire.h>
#include <Time.h>
#include <TimeAlarms.h>
#include <DS1307RTC.h>

int fan = 4;
int light = 7;

void setup () {
   
 Serial.begin(57600);
   Wire.begin();
   
   setSyncProvider(RTC.get);
   
   pinMode(fan, OUTPUT);
   pinMode(light, OUTPUT);
   digitalWrite(fan, HIGH);
   digitalWrite(light, HIGH);
   
   Alarm.alarmRepeat(2, 14, 0, LightsOn);
   Alarm.alarmRepeat(2, 14, 0, FanOn);

 }
 
void loop () {
 
   Alarm.delay(1);
 
}

void LightsOn() {
digitalWrite(light, LOW); // Set Lights On
   Serial.println("Lights On");
 delay(90000);
 LightsOff();  
}



void FanOn() {
digitalWrite(fan, LOW); // Set Fan On
   Serial.println("Fan On");
  delay(90000);
   FanOff();
}


void LightsOff() {
digitalWrite(light, HIGH); // Set Lights Off
  Serial.println("Lights Off");  
}

void FanOff() {
digitalWrite(fan, HIGH); // Set Fan Off
   Serial.println("Fan Off");
}


later edit:
I think I managed to make both alarms start together. I had to remove the delay from each function that the alarm calls, and then make another alarm to call the Off function.
Still I'd love some pointers on how can I manage to make alarms and after a power failure, if they were scheduled to be active (or call a function for a specified amount of time) have them active again. Something like check On and Off alarms and if in between at bootup activate On function if between Off and On alarms activate Off function.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: JimboZA on Sep 08, 2014, 06:07 am
Quote
I think I managed to make both alarms start together. I had to remove the delay from each function that the alarm calls, and then make another alarm to call the Off function.


I was going to suggest exactly that but then saw your edit. Delay() always blocks, so I think the way you have it now, with explicit offs from other alarms, is the right way.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 08, 2014, 02:01 pm
Yes, but with me wanting to add a LCD with keys I don't know if this approach is good. Wanting to program the On/Off cycles externally from LCD and storing the data into an EEPROM I don't know if this is the best way. I am having a tough time with redundancy at power failure.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: joe4444 on Sep 08, 2014, 10:13 pm
Hi all

I have finally gotten a chance to add time to my arduino and started with the DS1302 and managed to stumble along and get time and alarmtime working with it and the DS1302. Thank you for the libraries.
]Today I purchased a DS1307 to tinker with too.

My question is around the TimeAlarms library.
I would like to create many alarms for specific dates and times.
In the readme.txt  I found this statement:
Quote
If you want to trigger once at a specified date and time you can use the trigger Once() method:
 Alarm. triggerOnce(time_t value,  explicitAlarm); // value specifies a date and time
(See the makeTime() method in the Time library to convert dates and times into time_t)


My questions are:

Is there a basic example or walk-through as to how to do this?
I have been combing the forums and even been through the 18 pages on this one. The examples included in the library don't show it either.
Have I missed something somewhere ?

Looking forward to any help or info or examples.

Thanks a million

Joe
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Docedison on Sep 09, 2014, 04:16 am
THis might be of use to you for your current issues but I wrote it for a Mega2560.. a year or so back

Doc
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Sep 09, 2014, 10:55 am
Quote
My question is around the TimeAlarms library.
I would like to create many alarms for specific dates and times.

Why? You've got a clock. You've got a computer. On any given pass through loop, see if it's time to do something. If so, do it. You can check hundreds of things in microseconds.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: joe4444 on Sep 09, 2014, 06:57 pm
@ BOB

Thank you kindly I have started maketime()/ breaktime () fucntions.

Wow that's a lot of code you have there :-)

Typical though.. the one thing I am looking for is a simple example (albeit a few lines of code) to create an alarm on a specific date. It's the one example that's missing from the Arduino cookbook and unless I have been speed-reading for the last 3 days there isn't this simple example on the forums or google for that matter (I stand corrected if I have missed something)

@ Pauls
Yip why indeed !
Why would one fly a kite with a key tied to its string in a storm ?
Why did stone-age man want fire ?
A point to ponder indeed.
And yes I neglected to mention, I would like to automatically switch an infrared light on for my puppy.

Is there any where I can find an example which I look at to see how it's done ?
I think this is what is needed:
Code: [Select]
Alarm. triggerOnce(time_t value,  puppyAlarm); // value specifies a date and time
and this
Code: [Select]

time_t puppyAlarm = (14,50,0,9,9,14,puppyEvent) ;

and later one
Code: [Select]
void puppyEvent()
{
Serial.print("hot dog!")
}


IF I'm on the right track here then the part I am struggling with is :
how to get the times entered into the time_t format.?

Pointers and tips welcome

Regards

Joe
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 16, 2014, 01:26 pm
It seems that I have another problem :)

I am storing the time on EEPROM, and have it read into 2 variables (hour and minute) and those variables are read by Alarms.
The thing is that if I have stored the alarm time on my EEPROM, at startup everything is fine, I do get the trigger on time.
But, if I dynamically change the EEPROM after the Arduino boot, then the alarms won't refresh.

Let me give you a bit of code so you understand:

Code: [Select]
void setup () {
 
 
    readEEPROM(0);          //read eeprom for alarm hour;
    onH=rec;               
    readEEPROM(1);          //read eeprom for alarm minute;
    onM=rec;               
    readEEPROM(2);         
    offH=rec;
    readEEPROM(3);         
    offM=rec;
   
    Alarm.alarmRepeat(onH, onM, 0, LightsOn);
    Alarm.alarmRepeat(offH, offM, 0, LightsOff);
    if (onH < resethour && offH > resethour)
    {
      LightsOn();
    }
    else if (onH == resethour && onM <= resetminute)
    {
      if (offH == resethour && offM > resetminute)
       {
         LightsOn();
         FanOn();
       }
     }
}


void loop () {
  Alarm.delay(1);
}

void LightsOn() {
digitalWrite(light, HIGH); // Set Lights On
    Serial.println("Lights On");
}

void LightsOff() {
digitalWrite(light, LOW); // Set Lights Off
   Serial.println("Lights Off"); 
}

void readEEPROM(unsigned int eeaddress)                //EEPROM read function
{
  //function for reading EEPROM address, may vary depending on chip used
}

void writeEEPROM( unsigned int eeaddress, byte data)   //EEPROM write function
{
  //function for writing EEPROM address, may vary depending on chip used
}





I also have a part where I can write the alarm times on EEPROM with buttons/LCD. So, the part in setup after the alarms basically is a redundancy for power failure. At boot it reads the EEPROM for times and sets the Alarms with those times. If I boot the board, everything is ok, alarm starts at times read from EEPROM.
The issue is when I re-write those values while the software is running. If I change those values, the alarms won't trigger on the new times that were written on the EEPROM. I tried adding:
Code: [Select]
readEEPROM(0);         
    onH=rec;               
    readEEPROM(1);       
    onM=rec;               
    readEEPROM(2);         
    offH=rec;
    readEEPROM(3);         
    offM=rec;

in void loop() so to have the values updated constantly but it seems that Alarms is stuck with the first values read at boot. Also adding alarms to loop didn't help.
Is there a way that the alarm times update in real time?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Sep 16, 2014, 01:41 pm
Quote
But, if I dynamically change the EEPROM after the Arduino boot, then the alarms won't refresh.

How do you do this? How do you make the existing instances aware of this change?

Your readEEPROM() function should NOT be diddling with a global variable. It should be returning a value.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Sep 16, 2014, 01:49 pm
If you want to change the value used by an alarm that has already been set up you need to use the Alarm.write() method.

From the TimeAlarms readme
Quote
write(ID,  value);  -  write the value (and enable) the alarm for the given ID
The ID is created when the alarm is first set and can be found by setting the alarm like this
Code: [Select]
ID = Alarm.alarmRepeat(onH, onM, 0, LightsOn);

You may also be able to do what you want by disabling the alarm and setting it again.  See the readme for details.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 16, 2014, 01:52 pm
I use the write eeprom function from the LCD menu:

Code: [Select]
void writeEEPROM( unsigned int eeaddress, byte data)   //EEPROM write function
{
 Wire.beginTransmission(addr);
 Wire.write((int)(eeaddress >> 8));   // MSB
 Wire.write((int)(eeaddress & 0xFF)); // LSB
 Wire.write(data);
 Wire.endTransmission();
 delay(15);
}


And I read it with the read eeprom function:
Code: [Select]
void readEEPROM(unsigned int eeaddress)                //EEPROM read function
 {
 Wire.beginTransmission(addr);
 Wire.write((int)(eeaddress >> 8));
 Wire.write((int)(eeaddress & 0xFF));
 Wire.endTransmission();
 Wire.requestFrom(addr, 1);
 rec=Wire.read();
 }


And I store that into a variable that is used by Alarms.

Code: [Select]
readEEPROM(0);          
   onH=rec;                
   readEEPROM(1);        
   onM=rec;                
   readEEPROM(2);        
   offH=rec;
   readEEPROM(3);        
   offM=rec;
    Alarm.alarmRepeat(onH, onM, 0, LightsOn);
    Alarm.alarmRepeat(offH, offM, 0, LightsOff);


My read function returns an int value.
So, I am re-writing those addresses on the EEPROM with the write function from the LCD menu, but those "new" values aren't reflected in Alarms. Alarms only reads that value at boot. And inserting Alarms into loop doesn't help either. That was the first thing I tried. Any suggestions ?
I want to automate this process, not having to initiate a newly set alarm by rebooting the Arduino. I guess I'm not asking for much. How can alarms be refreshed automatically during program time?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Sep 16, 2014, 02:03 pm
Quote
My read function returns an int value.

No, it doesn't.

The write function takes an int address and a byte value. The read function takes an int address and stores a byte in a global variable. It is not clear from your snippets what type rec is, but the function does not return anything and it does not read an int.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 16, 2014, 02:22 pm
rec is declared as byte.
My read write functions work, I checked in serial monitor with Serial.print(onH) etc. Aaaaand! My Alarms fire at time IF I reboot the Arduino. So, my read write functions do their job very good.
How else would the alarms fire at the exact time that is written (previous to reboot) by me, from LCD menu, with the write function on eeprom? the alarm times are written successfully by the write funtion on the eeprom, then the read function puts those times into alarm. I have checked that the times are written to EEPROM with serial.print, then the alarms fire on the times written on the EEPROM at reboot, they do work ok. the problem is, if I change those times on the EEPROM while the program is running, the alarms don't refresh. how can I do that? :)

//edit:
If you have a 24LC256 eeprom please test my code to see that it works. why would I lie?


@UKHeliBob
I will look into it, thx
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Sep 16, 2014, 02:30 pm
Quote
why would I lie?

The statements you made were indeed incorrect. That is not the same, necessarily, as lying.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 16, 2014, 02:36 pm
Well, I said the functions work, that they write and read from the EEPROM, and that the alarms fire on those values, but only at reboot :)
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 16, 2014, 02:40 pm
Forgot to add that onH,onM,offH,offM are declared as int.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Sep 16, 2014, 02:40 pm
Quote
but only at reboot

Have you waited 24 hours to see if they fire again?

Have you showed us the code where you write new data to EEPROM? No.
Have you showed us code where you re-read that data? No.
Have you showed us code where you apply those values to the existing instances? No.
Have you showed us anything other than a snippet or two? No.
Can you reasonably expect help, then? No.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 16, 2014, 02:52 pm
You having a bad day?  :P

So,

I showed you where I read the data:

Code: [Select]
void setup () {
 
 
    readEEPROM(0);          //read eeprom for alarm hour;
    onH=rec;               
    readEEPROM(1);          //read eeprom for alarm minute;
    onM=rec;               
    readEEPROM(2);         
    offH=rec;
    readEEPROM(3);         
    offM=rec;
   
    Alarm.alarmRepeat(onH, onM, 0, LightsOn);
    Alarm.alarmRepeat(offH, offM, 0, LightsOff);



Also I apply those values to Alarm.alarmRepeat. onH/onM/offH/offM are integers with values from the read function "readEEPROM". and those integers go to alarm command. So I showed you that.
What else do you want me to show you? If you are in the "know" why would you want the whole code? I explained the structure and gave plenty of info.
I DO expect help, seems that just not from you at the moment...

Code: [Select]
#include <Wire.h>
#include <Time.h>
#include <TimeAlarms.h>
#include <DS1307RTC.h>
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int addr = 0x52;
const int light = 7;
byte resethour,resetmin,rec;
int  onH,onM,offH,offM,address,t;;
static tmElements_t tm;
 


void setup () {
   
    Serial.begin(57600);
    Wire.begin();
    setSyncProvider(RTC.get);
     pinMode(light, OUTPUT);
     digitalWrite(light, LOW);

    writeEEPROM(0,14);      //manual alarm time input on eeprom. will be made from UI.
    writeEEPROM(1,0);      //
    writeEEPROM(2,14);      //
    writeEEPROM(3,17);      //




    readEEPROM(0);         
    onH=rec;               
    readEEPROM(1);         
    onM=rec;               
    readEEPROM(2);         
    offH=rec;
    readEEPROM(3);       
    offM=rec;
     Alarm.alarmRepeat(onH, onM, 0, LightsOn);
     Alarm.alarmRepeat(offH, offM, 0, LightsOff);
    int resethour = hour();
    int resetminute = minute();
    if (onH < resethour && offH > resethour)
    {
      LightsOn();
    }
    else if (onH == resethour && onM <= resetminute)
    {
      if (offH == resethour && offM > resetminute)
       {
         LightsOn();
       }
     }
}
 
void loop () {
  Alarm.delay(1);
}

void LightsOn() {                         // Set Lights On
digitalWrite(light, HIGH);
    Serial.println("Lights On");
}



void LightsOff() {                         // Set Lights Off
digitalWrite(light, LOW);
   Serial.println("Lights Off"); 
}



void writeEEPROM( unsigned int eeaddress, byte data)   //EEPROM write function
{
  Wire.beginTransmission(addr);
  Wire.write((int)(eeaddress >> 8));   // MSB
  Wire.write((int)(eeaddress & 0xFF)); // LSB
  Wire.write(data);
  Wire.endTransmission();
  delay(15);
}

void readEEPROM(unsigned int eeaddress)                //EEPROM read function
  {
  Wire.beginTransmission(addr);
  Wire.write((int)(eeaddress >> 8));
  Wire.write((int)(eeaddress & 0xFF));
  Wire.endTransmission();
  Wire.requestFrom(addr, 1);
  rec=Wire.read();
  }



More code, at beginning of Setup you see some eeprom write functions. Those were used at first phase of testing, but didn't know that I'd have these problems. As they were first written the immediately read and dumped into alarms. Now I have a different code that writes those values AFTER boot, and after the values from the EEPROM have been read by the read commands and dumped into alarms.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 16, 2014, 02:58 pm

Quote
but only at reboot

Have you waited 24 hours to see if they fire again?


You don't get it.
Alarms FIRE, but on the time read at boot, from the EEPROM.
They WILL fire again, but at those "old" times.
They do NOT fire on the times written to eeprom AFTER boot. They most definitely  fire on the times that were read from the eeprom at boot. That's for sure. I tested it. It's easy to understand.
I wanted to know how to update the alarm times after boot, after they got the times from the EEPROM with:
Code: [Select]
readEEPROM(0);         
    onH=rec;               
    readEEPROM(1);         
    onM=rec;               
    readEEPROM(2);         
    offH=rec;
    readEEPROM(3);       
    offM=rec;


That bit of code is in setup(). That's read at startup, and it sets the alarm from the eeprom time.
Arduino Boot - read eeprom - set those values in the alarm function - alarm triggers at that time.
my problem:
Arduino Boot - read eeprom - set those valuies in alarm function (will call it "old time") - alarms will trigger at that time - me setting up new values in eeprom ( will call it "new time") - arduino does not fire on "new time", but fires on "old time".
My problem: how to reflect changes ("new time") in alarms function.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Sep 16, 2014, 03:15 pm
Quote
You having a bad day?

Nope. Are you?

Quote
Also I apply those values to Alarm.alarmRepeat. onH/onM/offH/offM are integers with values from the read function "readEEPROM". and those integers go to alarm command. So I showed you that.

You do that in setup(), which runs ONCE. You do not read EEPROM anywhere else. You don't write to EEPROM anywhere other than setup(), either. So, it is not surprising that the times that the alarms happen never changes.

Quote
If you are in the "know" why would you want the whole code?

So that I can confirm that the statements you've made are true. They are not, since you never change the values in EEPROM except at bootup, and you never read the values except in setup().

Quote
Now I have a different code that writes those values AFTER boot, and after the values from the EEPROM have been read by the read commands and dumped into alarms.

But, you aren't going to share that code. I see. Good day.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 16, 2014, 03:27 pm
I tried adding the readeeprom in loop but there was no change. My lcd code uses a menu library, can't paste it as I'm not home anymore. That wouldn't help you.
What I'm saying is that even if I put :
readEEPROM(0);         
    onH=rec;               
    readEEPROM(1);         
    onM=rec;               
    readEEPROM(2);         
    offH=rec;
    readEEPROM(3);       
    offM=rec;

In loop, it doesn't make any changes. OnH etc get updated, alsrms does not update on those variables. I can serial.print from loop, i see the new values. Alarms does not reflect with those values.
So far you haven't said anything, you posted for nothing. If you don't know what it's all about, why post?
Or maybe you cannot understand, and that's fine, but don't waste my time with posts that tell me nothing.
UKHeliBob understood and offered an idea. You just post no content.
I am pretty sure most people who read what I said got the idea.
So, even if I read the values in loop, the alarm doesn't reflect them. And i know I should not put alarms in loop.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Sep 16, 2014, 03:36 pm
Quote
OnH etc get updated, alsrms does not update on those variables.

Because the alarm time is not bound to the value in OnH. The VALUE in OnH is passed to the Alarm instance when the instance is created.

UKHeliBob explained what you need to do to update the existing instance(s) with the new data.

Quote
So far you haven't said anything, you posted for nothing. If you don't know what it's all about, why post?

I do know what it's all about, and how to solve your problem. I've been waiting to see if you were doing something wrong in the code, or simply making incorrect assumptions about what the code you have should be doing. You've finally posted enough information to confirm that it is the latter.

Quote
Or maybe you cannot understand, and that's fine, but don't waste my time with posts that tell me nothing.

You are the one wasting time not posting all the code that illustrates the problem you are having.

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: EnigmaCypher7 on Sep 16, 2014, 04:09 pm
Bob808,

Though this will not help your post, I understand your frustration. New users or users who want to become more informed come to this forum hoping to gain an understanding, just to be let down by a few users who post with an overinflated sense of themselves. The unfortunate part is some of these users post on everything... Before Paul gets infuriated and comments on my post, I would like to say I know you. Paul is one of the few users who is a bit difficult to work and usually keeps me steered away from this forum.

Not to advertise or anything but I have found great Arduino resources on Instructables.com and http://www.circuitsathome.com. Both have knowledgeable members who do not try to inflame their own issues and agendas.

Paul, try to have some patience and compassion. People come here to learn.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Sep 16, 2014, 04:26 pm
Quote
Paul, try to have some patience and compassion. People come here to learn.

The only way that can happen is for those people to admit that they might be doing something wrong, without getting defensive, and to be prepared to answer questions.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 16, 2014, 05:43 pm
Oh God, but ofcourse I don't understand something... That's why I posted here. Else I would just email the author that his library is broken :)))
I admit that I don't understand some things, or that I got them wrong.
Why would I post here?
The name of the thread implies it!
"Time and TimeAlarms Libraries - Ask here for help or suggestions "
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Sep 16, 2014, 07:29 pm
It's time for everyone to take a deep breath and calm down.

He might not agree but PaulS can be abrasive at times, but he does know his stuff.  I think what come through is his frustration that people appear not to take note of his suggestions and comments.  Mind you, I know how he feels having suggested how to reset an alarm with new values with no sign that the OP has tried it.

So I suggest that we start again.  Please post your code as it currently stands, describe the problem and let's see if we can make some progress.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cattledog on Sep 16, 2014, 07:44 pm
Bob 808--
I realize this thread involves time alarms, but I can see that you are not reading and writing your values to the eeprom correctly.

You are leaving out the I2C address of the eeprom. It is the addr in the Wire.beginTransmission line. There are two address to be concerned about, the device address of the eeprom, and the storage address within the eeprom(what you call eeaddress). From one of your earlier posts, it looks like the eeprom (24C32?) address is 0x52.

Additionally, the read EEPROM function should not be void, but have a byte return.

Code: [Select]
void writeEEPROM(unsigned int eeaddress, byte data)   //EEPROM write function
{
  Wire.beginTransmission(addr);
  Wire.write((int)(eeaddress >> 8));   // MSB
  Wire.write((int)(eeaddress & 0xFF)); // LSB
  Wire.write(data);
  Wire.endTransmission();
  delay(15);
}


Code: [Select]
void readEEPROM(unsigned int eeaddress)                //EEPROM read function
  {
  Wire.beginTransmission(addr);
  Wire.write((int)(eeaddress >> 8));
  Wire.write((int)(eeaddress & 0xFF));
  Wire.endTransmission();
  Wire.requestFrom(addr, 1);
  rec=Wire.read();
  }


These functions should be

Code: [Select]
void writeEEPROM(int addr, unsigned int eeaddress, byte data)   //EEPROM write function
{
  Wire.beginTransmission(addr);
  Wire.write((int)(eeaddress >> 8));   // MSB
  Wire.write((int)(eeaddress & 0xFF)); // LSB
  Wire.write(data);
  Wire.endTransmission();
  delay(15);


Code: [Select]
byte readEEPROM(int addr, unsigned int eeaddress)                //EEPROM read function
  {
  byte rec = 0;
  Wire.beginTransmission(addr);
  Wire.write((int)(eeaddress >> 8));
  Wire.write((int)(eeaddress & 0xFF));
  Wire.endTransmission();
  Wire.requestFrom(addr, 1);
  rec=Wire.read();
  return = rec;
  }


And when you call them you need to include all the parameters

Code: [Select]
readEEPROM (addr, eeaddress)
Code: [Select]
writeEEPROM(addr, eeaddress, data)
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 16, 2014, 10:54 pm
Sorry, I was out and could only be bothered to answer to Paul :)
Let me catch up and be right back.
As a quick note, I see that indeed The read write functions do the job I need, they write on the eeprom, i delete the write function call, call the read function, re-upload the code and on serial monitor I get the previously written info.
So I presumed it works. Also addr is defined at the begining as 0x52. It is a 24lc256. I have another 24c32 on the i2c line soldered on the ds1307 pcb. Didn't want to use that one (has 0x50) as I might make a write loop by mistake and damage the chip. It's nice to have on the same pcb with the clock for further projects.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 16, 2014, 11:50 pm
Meanwhile here's my complete code. I used a few sketches while building various parts of the final code, like menu and eeprom management and alarms etc. So here's the complete code:

Code: [Select]
#include <Wire.h>
#include <Time.h>
#include <TimeAlarms.h>
#include <DS1307RTC.h>
#include <LiquidCrystal.h>
#include "M2tk.h"
#include "utility/m2ghlc.h"

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

uint8_t uiKeySelectPin = A3;
int addr = 0x52;
const int light = 7;
byte rec,data;
int address,t,resethour,resetminute;

uint8_t t_hours = 0;
uint8_t t_minutes = 0;
uint8_t a_hours = 0;
uint8_t a_minutes = 0;

int  onH,onM,offH,offM =0;
static tmElements_t tm;
 

M2_EXTERN_HLIST(top_el_expandable_menu);
M2_LABEL(el_set_time, "x5y3", "Start Time:");
M2_LABEL(el_ht, "x3y2", "hour   -");
M2_U8NUM(el_t_hour, "x12y2c2", 0, 23, &t_hours);
M2_LABEL(el_mt, "x3y1", "minute -");
M2_U8NUM(el_t_minute, "x12y1c2", 0, 59, &t_minutes);
M2_BUTTON(el_set_t, "x3y0", "set", write_t_time);
M2_BUTTON(el_back_t, "x10y0", "back", fn_back);
M2_LIST(timelist) = {&el_set_time, &el_ht, &el_mt, &el_t_hour, &el_t_minute, &el_set_t, &el_back_t};
M2_XYLIST(el_set_Time, NULL, timelist);
M2_LABEL(el_set_alarm, "x5y3", "Stop Time:");
M2_LABEL(el_ah, "x3y2", "hour   -");
M2_U8NUM(el_a_hour, "x12y2c2", 0, 23, &a_hours);
M2_LABEL(el_am, "x3y1", "minute -");
M2_U8NUM(el_a_minute, "x12y1c2", 0, 59, &a_minutes);
M2_BUTTON(el_set_a, "x3y0", "set", write_a_time);
M2_BUTTON(el_back_a, "x10y0", "back", fn_back);
M2_LIST(alarmlist) = {&el_set_alarm, &el_ah, &el_am, &el_a_hour, &el_a_minute, &el_set_a, &el_back_a};
M2_XYLIST(el_set_Alarm, NULL, alarmlist);
m2_menu_entry m2_2lmenu_data[] =
{
  { "Set Light", NULL },
  { ". Start Time:", &el_set_Time },
  { ". Stop Time:", &el_set_Alarm },
  { NULL, NULL },
};
uint8_t m2_2lmenu_first;
uint8_t m2_2lmenu_cnt;
M2_2LMENU(el_2lmenu,"l4e1w12", NULL, &m2_2lmenu_cnt, m2_2lmenu_data, NULL, NULL, '\0');
M2_LIST(list_2lmenu) = { &el_2lmenu};
M2_HLIST(top_el_expandable_menu, NULL, list_2lmenu);
M2tk m2(&top_el_expandable_menu, m2_es_arduino_rotary_encoder, m2_eh_4bd, m2_gh_lc);

void setup () {
   
    Serial.begin(57600);
    Wire.begin();
    lcd.begin(20, 4);
    setSyncProvider(RTC.get);
     pinMode(light, OUTPUT);
     digitalWrite(light, LOW);
      m2_SetLiquidCrystal(&lcd, 20, 4);
      m2.setPin(M2_KEY_SELECT, uiKeySelectPin);
      m2.setPin(M2_KEY_ROT_ENC_A, A0);
      m2.setPin(M2_KEY_ROT_ENC_B, A1);
    readEEPROM(0);         
    onH=rec;               
    readEEPROM(1);         
    onM=rec;               
    readEEPROM(2);         
    offH=rec;
    readEEPROM(3);       
    offM=rec;
     Alarm.alarmRepeat(onH, onM, 0, LightsOn);
     Alarm.alarmRepeat(offH, offM, 0, LightsOff);
    int resethour = hour();
    int resetminute = minute();
    if (onH < resethour && offH > resethour)
    {
      LightsOn();
    }
    else if (onH == resethour && onM <= resetminute)
    {
      if (offH == resethour && offM > resetminute)
       {
         LightsOn();
       }
     LightsOn();
   }
}

 
void loop () {
   m2.checkKey();
   m2.checkKey();
    if ( m2.handleKey() )
     m2.draw();
   m2.checkKey();
Alarm.delay(1);

}

void LightsOn() {                         // Set Lights On
digitalWrite(light, HIGH);
    Serial.println("Lights On");
}



void LightsOff() {                         // Set Lights Off
digitalWrite(light, LOW);
   Serial.println("Lights Off"); 
}


void writeEEPROM( unsigned int eeaddress, byte data)   //EEPROM write function
{
  Wire.beginTransmission(addr);
  Wire.write((int)(eeaddress >> 8));   // MSB
  Wire.write((int)(eeaddress & 0xFF)); // LSB
  Wire.write(data);
  Wire.endTransmission();
  delay(15);
}

void readEEPROM(unsigned int eeaddress)                //EEPROM read function
  {
  Wire.beginTransmission(addr);
  Wire.write((int)(eeaddress >> 8));
  Wire.write((int)(eeaddress & 0xFF));
  Wire.endTransmission();
  Wire.requestFrom(addr, 1);
  rec=Wire.read();
  }

void fn_back(m2_el_fnarg_p fnarg)   // back button
  {
    m2.setRoot(&top_el_expandable_menu);
  }
 
void write_t_time(m2_el_fnarg_p fnarg) // set ON time
  {
   writeEEPROM(0,t_hours);
   writeEEPROM(1,t_minutes);
   lcd.clear();
   lcd.setCursor(8,1);
   lcd.print("Set!");
   delay(1000);
  }

void write_a_time(m2_el_fnarg_p fnarg) // set OFF time
  {
   writeEEPROM(2,a_hours);
   writeEEPROM(3,a_minutes);
   lcd.clear();
   lcd.setCursor(8,1);
   lcd.print("Set!");
   delay(1000);
  }


This bit is the redundancy for power failure. I haven't figured it out completely but for start hour 00:00 and stop hour 01:00 and I reset it at 00:30 it works. I just tested it again, it works, it starts the alarm at boot, and stops on the clock. If start time is 00:05, and current time is 00:03, after boot, in 2 minutes the alarm triggers. The alarm times are ALL read out from the eeprom, the functions work, as they are defined now.

Code: [Select]
int resethour = hour();
    int resetminute = minute();
    if (onH < resethour && offH > resethour)
    {
      LightsOn();
    }
    else if (onH == resethour && onM <= resetminute)
    {
      if (offH == resethour && offM > resetminute)
       {
         LightsOn();
       }
     LightsOn();
   }



I'm not saying that it's better some other ways. I'm just saying that these are my results.
Also I have to look at the read function as it's declared void not byte. I still have a lot to learn.

The LCD menu library is m2tklib developed by olikraus member here on this forum. He's been a real gent in working with me to figure out the way it works, and I wrapped my head around most of the code that I use from his library.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 17, 2014, 01:18 am
I tried it with Alarm.write but doesn't seem to work either. I'm calling it when I set the on/off times.

Code: [Select]
#include <Wire.h>
#include <Time.h>
#include <TimeAlarms.h>
#include <DS1307RTC.h>
#include <LiquidCrystal.h>
#include "M2tk.h"
#include "utility/m2ghlc.h"

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

uint8_t uiKeySelectPin = A3;
int addr = 0x52;
const int light = 7;
byte rec,data;
int address,t,resethour,resetminute;

uint8_t t_hours = 0;
uint8_t t_minutes = 0;
uint8_t a_hours = 0;
uint8_t a_minutes = 0;

int  onH,onM,offH,offM =0;
static tmElements_t tm;

AlarmID_t on, off;  

M2_EXTERN_HLIST(top_el_expandable_menu);
M2_LABEL(el_set_time, "x5y3", "Start Time:");
M2_LABEL(el_ht, "x3y2", "hour   -");
M2_U8NUM(el_t_hour, "x12y2c2", 0, 23, &t_hours);
M2_LABEL(el_mt, "x3y1", "minute -");
M2_U8NUM(el_t_minute, "x12y1c2", 0, 59, &t_minutes);
M2_BUTTON(el_set_t, "x3y0", "set", write_t_time);
M2_BUTTON(el_back_t, "x10y0", "back", fn_back);
M2_LIST(timelist) = {&el_set_time, &el_ht, &el_mt, &el_t_hour, &el_t_minute, &el_set_t, &el_back_t};
M2_XYLIST(el_set_Time, NULL, timelist);
M2_LABEL(el_set_alarm, "x5y3", "Stop Time:");
M2_LABEL(el_ah, "x3y2", "hour   -");
M2_U8NUM(el_a_hour, "x12y2c2", 0, 23, &a_hours);
M2_LABEL(el_am, "x3y1", "minute -");
M2_U8NUM(el_a_minute, "x12y1c2", 0, 59, &a_minutes);
M2_BUTTON(el_set_a, "x3y0", "set", write_a_time);
M2_BUTTON(el_back_a, "x10y0", "back", fn_back);
M2_LIST(alarmlist) = {&el_set_alarm, &el_ah, &el_am, &el_a_hour, &el_a_minute, &el_set_a, &el_back_a};
M2_XYLIST(el_set_Alarm, NULL, alarmlist);
m2_menu_entry m2_2lmenu_data[] =
{
 { "Set Light", NULL },
 { ". Start Time:", &el_set_Time },
 { ". Stop Time:", &el_set_Alarm },
 { NULL, NULL },
};
uint8_t m2_2lmenu_first;
uint8_t m2_2lmenu_cnt;
M2_2LMENU(el_2lmenu,"l4e1w12", NULL, &m2_2lmenu_cnt, m2_2lmenu_data, NULL, NULL, '\0');
M2_LIST(list_2lmenu) = { &el_2lmenu};
M2_HLIST(top_el_expandable_menu, NULL, list_2lmenu);
M2tk m2(&top_el_expandable_menu, m2_es_arduino_rotary_encoder, m2_eh_4bd, m2_gh_lc);

void setup () {
   
   Serial.begin(57600);
   Wire.begin();
   lcd.begin(20, 4);
   setSyncProvider(RTC.get);
    pinMode(light, OUTPUT);
    digitalWrite(light, LOW);
     m2_SetLiquidCrystal(&lcd, 20, 4);
     m2.setPin(M2_KEY_SELECT, uiKeySelectPin);
     m2.setPin(M2_KEY_ROT_ENC_A, A0);
     m2.setPin(M2_KEY_ROT_ENC_B, A1);
   readEEPROM(addr,0);          
   onH=rec;                
   readEEPROM(addr,1);        
   onM=rec;                
   readEEPROM(addr,2);        
   offH=rec;
   readEEPROM(addr,3);        
   offM=rec;
   on = Alarm.alarmRepeat(onH, onM, 0, LightsOn);
   off = Alarm.alarmRepeat(offH, offM, 0, LightsOff);
time_t newTime = AlarmHMS(onH,onM,00);
Alarm.write(on,newTime);

   int resethour = hour();
   int resetminute = minute();
   if (onH < resethour && offH > resethour)
   {
     LightsOn();
   }
   else if (onH == resethour && onM <= resetminute)
   {
     if (offH == resethour && offM > resetminute)
      {
        LightsOn();
      }
    LightsOn();
  }
}

 
void loop () {
  m2.checkKey();
  m2.checkKey();
   if ( m2.handleKey() )
    m2.draw();
  m2.checkKey();
Alarm.delay(1);

}

void LightsOn() {                         // Set Lights On
digitalWrite(light, HIGH);
   Serial.println("Lights On");
}



void LightsOff() {                         // Set Lights Off
digitalWrite(light, LOW);
  Serial.println("Lights Off");  
}


void writeEEPROM(int addr, unsigned int eeaddress, byte data)   //EEPROM write function
{
 Wire.beginTransmission(addr);
 Wire.write((int)(eeaddress >> 8));   // MSB
 Wire.write((int)(eeaddress & 0xFF)); // LSB
 Wire.write(data);
 Wire.endTransmission();
 delay(15);
}

byte readEEPROM(int addr, unsigned int eeaddress)                //EEPROM read function
 {
 Wire.beginTransmission(addr);
 Wire.write((int)(eeaddress >> 8));
 Wire.write((int)(eeaddress & 0xFF));
 Wire.endTransmission();
 Wire.requestFrom(addr, 1);
 rec=Wire.read();
 }

void fn_back(m2_el_fnarg_p fnarg)   // back button
 {
   m2.setRoot(&top_el_expandable_menu);
 }
 
void write_t_time(m2_el_fnarg_p fnarg) // set ON time
 {
  writeEEPROM(addr,0,t_hours);
  writeEEPROM(addr,1,t_minutes);
   readEEPROM(addr,0);          
   onH=rec;                
   readEEPROM(addr,1);        
   onM=rec;                
  time_t newTime = AlarmHMS(onH,onM,00);
  Alarm.write(on,newTime);
  Serial.print("On:");
  Serial.print(onH);
  Serial.print(":");
  Serial.println(onM);
  lcd.clear();
  lcd.setCursor(8,1);
  lcd.print("Set!");
  delay(1000);
 }

void write_a_time(m2_el_fnarg_p fnarg) // set OFF time
 {
  writeEEPROM(addr,2,a_hours);
  writeEEPROM(addr,3,a_minutes);
  readEEPROM(addr,2);          
   offH=rec;                
   readEEPROM(addr,3);        
   offM=rec;                
  time_t newTimea = AlarmHMS(offH,offM,00);
  Alarm.write(off,newTimea);
  Serial.print("Off:");
  Serial.print(offH);
  Serial.print(":");
  Serial.println(offM);
  lcd.clear();
  lcd.setCursor(8,1);
  lcd.print("Set!");
  delay(1000);
 }
 



Serial.print is there so I see that the values were stored&read from the eeprom when I set the times.

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 17, 2014, 02:05 am
Made something else, I found some code that mem wrote, to print on serial the current time and the time that the alarms are set.
I put that in loop, and watched the serial monitor as time went by.
If I boot the arduino with 1 minute before ON time then the alarm fires properly. If I set the time from the menu with 1-2 minutes before I set it to fire, it does NOT fire. To see if the alarms get updated, I put this code so I can check what's happening, if the alarms are getting updated.

This is the complete code used:
Code: [Select]
#include <Wire.h>
#include <Time.h>
#include <TimeAlarms.h>
#include <DS1307RTC.h>
#include <LiquidCrystal.h>
#include "M2tk.h"
#include "utility/m2ghlc.h"

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

uint8_t uiKeySelectPin = A3;
int addr = 0x52;
const int light = 7;
byte rec,data;
int address,t,resethour,resetminute;

uint8_t t_hours = 0;
uint8_t t_minutes = 0;
uint8_t a_hours = 0;
uint8_t a_minutes = 0;

int  onH,onM,offH,offM =0;
static tmElements_t tm;

AlarmID_t on, off;  

M2_EXTERN_HLIST(top_el_expandable_menu);
M2_LABEL(el_set_time, "x5y3", "Start Time:");
M2_LABEL(el_ht, "x3y2", "hour   -");
M2_U8NUM(el_t_hour, "x12y2c2", 0, 23, &t_hours);
M2_LABEL(el_mt, "x3y1", "minute -");
M2_U8NUM(el_t_minute, "x12y1c2", 0, 59, &t_minutes);
M2_BUTTON(el_set_t, "x3y0", "set", write_t_time);
M2_BUTTON(el_back_t, "x10y0", "back", fn_back);
M2_LIST(timelist) = {&el_set_time, &el_ht, &el_mt, &el_t_hour, &el_t_minute, &el_set_t, &el_back_t};
M2_XYLIST(el_set_Time, NULL, timelist);
M2_LABEL(el_set_alarm, "x5y3", "Stop Time:");
M2_LABEL(el_ah, "x3y2", "hour   -");
M2_U8NUM(el_a_hour, "x12y2c2", 0, 23, &a_hours);
M2_LABEL(el_am, "x3y1", "minute -");
M2_U8NUM(el_a_minute, "x12y1c2", 0, 59, &a_minutes);
M2_BUTTON(el_set_a, "x3y0", "set", write_a_time);
M2_BUTTON(el_back_a, "x10y0", "back", fn_back);
M2_LIST(alarmlist) = {&el_set_alarm, &el_ah, &el_am, &el_a_hour, &el_a_minute, &el_set_a, &el_back_a};
M2_XYLIST(el_set_Alarm, NULL, alarmlist);
m2_menu_entry m2_2lmenu_data[] =
{
 { "Set Light", NULL },
 { ". Start Time:", &el_set_Time },
 { ". Stop Time:", &el_set_Alarm },
 { NULL, NULL },
};
uint8_t m2_2lmenu_first;
uint8_t m2_2lmenu_cnt;
M2_2LMENU(el_2lmenu,"l4e1w12", NULL, &m2_2lmenu_cnt, m2_2lmenu_data, NULL, NULL, '\0');
M2_LIST(list_2lmenu) = { &el_2lmenu};
M2_HLIST(top_el_expandable_menu, NULL, list_2lmenu);
M2tk m2(&top_el_expandable_menu, m2_es_arduino_rotary_encoder, m2_eh_4bd, m2_gh_lc);

void setup () {
   
   Serial.begin(57600);
   Wire.begin();
   lcd.begin(20, 4);
   setSyncProvider(RTC.get);
    pinMode(light, OUTPUT);
    digitalWrite(light, LOW);
     m2_SetLiquidCrystal(&lcd, 20, 4);
     m2.setPin(M2_KEY_SELECT, uiKeySelectPin);
     m2.setPin(M2_KEY_ROT_ENC_A, A0);
     m2.setPin(M2_KEY_ROT_ENC_B, A1);
   readEEPROM(addr,0);          
   onH=rec;                
   readEEPROM(addr,1);        
   onM=rec;                
   readEEPROM(addr,2);        
   offH=rec;
   readEEPROM(addr,3);        
   offM=rec;
   on = Alarm.alarmRepeat(onH, onM, 0, LightsOn);
   off = Alarm.alarmRepeat(offH, offM, 0, LightsOff);
//time_t newTime = AlarmHMS(onH,onM,00);
//Alarm.write(on,newTime);
/*
   int resethour = hour();
   int resetminute = minute();
   if (onH < resethour && offH > resethour)
   {
     LightsOn();
   }
   else if (onH == resethour && onM <= resetminute)
   {
     if (offH == resethour && offM > resetminute)
      {
        LightsOn();
      }
    LightsOn();
  }
*/
}

 
void loop () {
  m2.checkKey();
  m2.checkKey();
   if ( m2.handleKey() )
    m2.draw();
  m2.checkKey();
  time_t t = now();
 digitalClockDisplay(t);
 Alarm.delay(10); // wait one second between clock display
 showAlarmTime(on);
 showAlarmTime(off);

//Alarm.delay(1);

}

void LightsOn() {                         // Set Lights On
digitalWrite(light, HIGH);
   Serial.println("Lights On");
}



void LightsOff() {                         // Set Lights Off
digitalWrite(light, LOW);
  Serial.println("Lights Off");  
}


void writeEEPROM(int addr, unsigned int eeaddress, byte data)   //EEPROM write function
{
 Wire.beginTransmission(addr);
 Wire.write((int)(eeaddress >> 8));   // MSB
 Wire.write((int)(eeaddress & 0xFF)); // LSB
 Wire.write(data);
 Wire.endTransmission();
 delay(15);
}

byte readEEPROM(int addr, unsigned int eeaddress)                //EEPROM read function
 {
 Wire.beginTransmission(addr);
 Wire.write((int)(eeaddress >> 8));
 Wire.write((int)(eeaddress & 0xFF));
 Wire.endTransmission();
 Wire.requestFrom(addr, 1);
 rec=Wire.read();
 }

void fn_back(m2_el_fnarg_p fnarg)   // back button
 {
   m2.setRoot(&top_el_expandable_menu);
 }
 
void write_t_time(m2_el_fnarg_p fnarg) // set ON time
 {
  writeEEPROM(addr,0,t_hours);
  writeEEPROM(addr,1,t_minutes);
   readEEPROM(addr,0);          
   onH=rec;                
   readEEPROM(addr,1);        
   onM=rec;                
  time_t newTime = AlarmHMS(onH,onM,0);
  Alarm.write(on,newTime);
 // Alarm.disable (on);  
//  Alarm.free (on);
  Serial.print("On:");
  Serial.print(onH);
  Serial.print(":");
  Serial.println(onM);
  lcd.clear();
  lcd.setCursor(8,1);
  lcd.print("Set!");
  delay(1000);
 }

void write_a_time(m2_el_fnarg_p fnarg) // set OFF time
 {
  writeEEPROM(addr,2,a_hours);
  writeEEPROM(addr,3,a_minutes);
  readEEPROM(addr,2);          
   offH=rec;                
   readEEPROM(addr,3);        
   offM=rec;                
  time_t newTimea = AlarmHMS(offH,offM,0);
  Alarm.write(off,newTimea);
 // Alarm.disable (off);  
 // Alarm.free (off);
  Serial.print("Off:");
  Serial.print(offH);
  Serial.print(":");
  Serial.println(offM);
  lcd.clear();
  lcd.setCursor(8,1);
  lcd.print("Set!");
  delay(1000);
 }
 
void showAlarmTime(AlarmID_t id)
{
 time_t alarmTime = Alarm.read(id);
 if(alarmTime!= 0)
 {
   if( alarmTime <= SECS_PER_DAY)  
      Serial.print(" repeat alarm with ID ");
   else  
       Serial.print(" once only alarm with ID  ");
   Serial.print(id, DEC);    
   Serial.print(" set for ");
   digitalClockDisplay(alarmTime);
 }  
}


void digitalClockDisplay(time_t t)
{
 // digital clock display of the time
 Serial.print(hour(t));
 printDigits(minute(t));
 printDigits(second(t));
 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);
}


So basically I could see on the serial monitor live, as I set the alarm times from the menu, they were reflected instantly on screen.
But when the time came, the alarms did NOT fire. Besides the LED no lighting up, I also have a serial message from the function that the alarm calls. That didn't came up either.
I attached the output of mem's code:

Code: [Select]
2:52:59
repeat alarm with ID 0 set for 2:53:00
repeat alarm with ID 1 set for 2:54:00
2:53:00
repeat alarm with ID 0 set for 2:53:00
repeat alarm with ID 1 set for 2:54:00
2:53:01
repeat alarm with ID 0 set for 2:53:00
repeat alarm with ID 1 set for 2:54:00



So now I can see clearly that the alarms are getting updated, what is going on?
If I set the alarms from the menu, let's say 2 minutes ahead of present time, and I reset the board, the alarms fire. And this is interesting, check the serial output:
Code: [Select]
3:03:59
repeat alarm with ID 0 set for 3:04:00
repeat alarm with ID 1 set for 3:05:00
3:03:59
Lights On
repeat alarm with ID 0 set for 3:04:00
repeat alarm with ID 1 set for 3:05:00
3:04:00
repeat alarm with ID 0 set for 3:04:00
repeat alarm with ID 1 set for 3:05:00

I get the message that the alarm has been triggered (as in, the function that the alarm triggers).
So now I need help :)
Paul?


//later edit:
also if I remove Alarm.write from the set time functions and I add it to loop() I get the same results.
Code: [Select]
void loop ()
{
..................................................................................................
    readEEPROM(addr,0);         
    onH=rec;               
    readEEPROM(addr,1);         
    onM=rec;               
    readEEPROM(addr,2);         
    offH=rec;
    readEEPROM(addr,3);       
    offM=rec;
time_t newTime = AlarmHMS(onH,onM,00);
time_t newTimea = AlarmHMS(offH,offM,00);
Alarm.write(on,newTime);
Alarm.write(off,newTimea);
..................................................................................................
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 17, 2014, 01:40 pm
Anyone have any ideas?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Sep 17, 2014, 01:56 pm

Anyone have any ideas?

You know what time it is. You know when you want things to happen. Do you really need a library to make that happen for you?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 17, 2014, 02:43 pm
Well, I went the library way at first as I didn't know any other way. I guess I will try setting the time and just if/then/else?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Sep 17, 2014, 02:50 pm
Quote
I guess I will try setting the time and just if/then/else?

then? This isn't Basic.

But, yeah, that's the simplest way.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 17, 2014, 03:21 pm
Great, thx.
I'll try it and come back with my results.
Although I guess it would be interesting to hear mem's opinion on my results with TimeAlarm library.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 17, 2014, 11:57 pm
I removed the whole alarms deal from my code.
Just added this to loop:
Code: [Select]
readEEPROM(addr,0);          
   onH=rec;                
   readEEPROM(addr,1);        
   onM=rec;                
   readEEPROM(addr,2);        
   offH=rec;
   readEEPROM(addr,3);        
   offM=rec;
   int nowh = hour();
    int nowm = minute();
    int nows = second();
  if (nowh == onH && nowm == onM && nows == 0)
  {
    LightsOn();
  }
 
  if (nowh == offH && nowm == offM && nows == 0)
  {
    LightsOff();
 
 }


Second is defined because I need it to trigger on exact time but not run the function for a whole minute, instead it calls it for a second that way.
Now I just need to make the if statements for redundancy,  and with hour and minutes values it's going to get a bit messy.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 18, 2014, 12:19 am
Creating redundancy for a program that spans from one day to the other is plain crazy.
Assuming start hour is 9 in the morning and end hour is 8 in the evening everything is good as it's a 24 hour format. IF(start hour<reset hour && stop hour > reset hour) then run function.
Get's a bit messy when start hour is 9:30 and stop hour is 20:30. As you can have a reset at 9:45 and you need to get into minutes conditions.
And then everything goes haywire when your start program is at 22 hours and stop program is at 3 in the morning, and the reset happens in between.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Sep 18, 2014, 12:30 am
Quote
And then everything goes haywire when your start program is at 22 hours and stop program is at 3 in the morning, and the reset happens in between.

I don't see why. You know something needs to start at some time. If it is that time, start it.
You know something needs to end at some time. If it is that time, stop it.

I think your problem is that you are thinking in terms of "it needs to start at x:xx and end at x:xx, and be called over and over again in between.

That's not the best way to do that. Think in terns of setting a thisProcessShoudlBeRunning flag to true if it is 9:00PM. Set it to false if it is 3:00AM.

Then, independent of the time, test the flag to see if the process should be running.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 18, 2014, 01:33 am
I don't know flags :)
So I should study some more.
I nailed the start stop time at the moment, it's doing it's job. Right now I'm interested in checking to see if it needs to be continuing the program at any power failure so I need to look into what you said.

I made it easier to compare times by creating a longer number from hours and minutes.
Code: [Select]

   int time = hour()*10000 + minute()*100 + second();
   int on = onH*10000 + onM*100;
   int off = offH*10000 + offM*100;

if (time == on)
{
  LightsOn();
}
if (time==off)
{
LightsOff();
}

For the start-up check I only used hours and minutes:
Code: [Select]

int time = hour()*100 + minute();
int on = onH*100 + onM;
int off = offH*100 + offM;
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 18, 2014, 01:42 am
the only thing in loop is the time comparing algorithm, and the math. the function gets called for the duration of a second when the time comes, and the off function as well. I don't know if there's a more efficient way to do it only for calling two functions at certain times. It may be, but I can't think of any.
It may be another way that incorporates the redundancy check and calls the functions at certain times, but I have no idea at the moment.


edit:
forgot to mention a critical aspect. the purpose of the contraption :)
So, it's meant to be used for an aquarium. Light/pump/feeder :)
At the moment I can scale the pump, I make it the same as the light, should be on for some time.
But the feeder is another story, as it has a short program of few seconds. If feeder is supposed to run at 10 o'clock and I have a power failure from 9:30 to 10:30 then the fish miss their breakfast :) And I'd worry while on vacation as power outs are common here.
So I'd have to implement some check bits that are written whenever it ran?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cattledog on Sep 18, 2014, 03:09 am
Quote
I don't know if there's a more efficient way to do it only for calling two functions at certain times. It may be, but I can't think of any.


Quote
I don't know flags smiley
So I should study some more.


The way to call your functions only once instead of multiple times in the one second where your test conditions match the reading of the clock is to use a flag.

Take a look at this post by JimboZA  http://forum.arduino.cc/index.php?topic=267077.msg1883433#msg1883433  which discusses using flags for just this purpose.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 18, 2014, 08:34 pm
Ok, I kind of got it, it's like a light switch but how does that help my redundancy?
I can't quite figure it out how to implement it, I mean the logic behind it.
The only benefit of flags right now is that the function gets called only once, not for a whole second (which is not much anyway, but for efficiency's sake let's say I'll do it).
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: JimboZA on Sep 18, 2014, 08:48 pm

The only benefit of flags right now is that the function gets called only once, not for a whole second (which is not much anyway, but for efficiency's sake let's say I'll do it).


Well it's more than that.... if you're switching on an LED at the start of the appropriate second and leaving it on for 5 minutes, yeah it's just a waste of effort but maybe no biggy if you re-switch it on a zillion times. But  in my case I was writing an eeprom and they have a limited number of writes before they wear out. In fact, an Arduino built-in eeprom can take 100k writes: loop() runs faster than 150k per second, so if I didn't prevent the writes after the first time, I'd wear out the eeprom in under a second. (Apart from the fact that I wanted the temp written at a specific time, not a minute later.)
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 18, 2014, 09:12 pm
Oh yes, I can totally understand that. I don't even use the eeprom on the RTC pcb :) as I don't want to "consume" it by mistake. I just use a breadboarded one.
Writing on EEPROM should only be called once if it is enough.
I'm just switching pins on and off so it really doesn't matter. But I want to get familiar with flags as I always wondered if I have something in loop and I need it to have a delay, then it would delay the whole loop so that's not always good.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 19, 2014, 12:32 am
I guess I've done it with flags. This way it works, I set the time, when the time comes the function gets called, the LED is on. When the Off time comes, LED goes off.
Also I've watched in console, the function gets called only one time, and the flag stays on for the whole second. For the OFF I've switched values as I'm using the flag value for the pin output value.
Here's a bit of code, tell me please if it's correctly implemented.



Code: [Select]
.............................
boolean alarm = false;
boolean alarm2 = true;
..............................................
void loop ()
{
...................................................
  readEEPROM(addr,0);          
   onH=rec;                
   readEEPROM(addr,1);        
   onM=rec;                
   readEEPROM(addr,2);        
   offH=rec;
   readEEPROM(addr,3);        
   offM=rec;

  int time = hour()*10000 + minute()*100+second();
  int on = onH*10000 + onM*100;
  int off = offH*10000 + offM*100;

if (time == on)
     {
             if(alarm == false)
                   {
                           alarm = true;
                           LightsOn();
                   }
      }
if (time !=on)
      {
              alarm= false;
       }

if (time==off)
      {
               if(alarm2==true)
                      {
                             alarm2 = false;
                             LightsOff();
                       }
        }
if(time !=off)
        {
 alarm2=true;
        }
}

void LightsOn()
          {                        
                 digitalWrite(light, alarm);
                 Serial.println("Lights On");
           }

void LightsOff()
         {                        
                 digitalWrite(light, alarm2);
                 Serial.println("Lights Off");  
          }





//later edit:
No, I didn't have it, but now I think I do. Each time on or off function are called they flip the flag.


Code: [Select]
.............................
boolean flag = false;

..............................................
void loop ()
{
...................................................
  readEEPROM(addr,0);          
   onH=rec;                
   readEEPROM(addr,1);        
   onM=rec;                
   readEEPROM(addr,2);        
   offH=rec;
   readEEPROM(addr,3);        
   offM=rec;

  int time = hour()*10000 + minute()*100+second();
  int on = onH*10000 + onM*100;
  int off = offH*10000 + offM*100;

if (time == on)
     {
             if(flag == false)
                   {                            
                           LightsOn();
                           flag = true;
                   }
      }


if (time==off)
      {
               if(flag == true)
                      {                              
                             LightsOff();
                             flag = false;
                       }
        }

}

void LightsOn()
          {                        
                 digitalWrite(light, HIGH);
                 Serial.println("Lights On");
           }

void LightsOff()
         {                        
                 digitalWrite(light, LOW);
                 Serial.println("Lights Off");  
          }
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 19, 2014, 01:28 am
And I think I nailed the redundancy as well.
Since I'm comparing integers instead of hours & minutes separately it's easier.
First, I need to write the flag to EEPROM each time it's changed. I guess that wouldn't be many writes for two on/off cycles a day.

This would be the code that takes care of power losses:

Code: [Select]
if (time > on && flag == true)
 {
     LightsOn();
 }
if (time < on && flag == true)
 {
   LightsOn();
 }


//later edit:

no, not enough, if the power-out began before the on function could run, the flag would be still false. and if it runs and the flag is true and then in the middle of the program the power goes out, it has a true flag, but it still has to run it.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 19, 2014, 04:08 am
I think I'm done this time with redundancy. It works out.
I also added a poorly made paint visual for all 8 cases that might happen at boot. Two major cases, where On time is smaller than Off time, and in reverse. One could call them "day time" and "night time". Each have their quirks.
In the photo there's the 24 hour span black line, the red line is the normal program of the light. The thicker black lines represent blackout periods, green 0/1 are the normal flags corresponding to each on/off state of the light and the blue 0/1 are the flags  read at boot from blackout.
I tested the code in a normal on<off flag=1 and on<reset<off and it triggered the LED.

Code: [Select]

boolean flag = false;
.............................
void setup(){
.............................
    readEEPROM(addr,0);         
    onH=rec;               
    readEEPROM(addr,1);         
    onM=rec;               
    readEEPROM(addr,2);         
    offH=rec;
    readEEPROM(addr,3);       
    offM=rec;
int time = hour()*100 + minute();
int on = onH*100 + onM;
int off = offH*100 + offM;
readEEPROM(addr,4);
flag = rec;

if(on<off){
                    if(time>on && time <off && flag == 1)
                      {
                        LightsOn();
                      }
                     if(time>on && time<off && flag == 0)
                      {
                        LightsOn();
                        writeEEPROM(addr,4,1);
                      }
                     if(time>on && time>off && flag == 1)
                      {
                        writeEEPROM(addr,4,0);
                      }
                     if(time<on && time<off && flag == 1)
                      {
                        writeEEPROM(addr,4,0);
                      }
}

if(on>off){
                    if(time>on && time>off && flag == 1)
                    {
                       LightsOn();
                    }
                    if(time<on && time<off && flag == 1)
                    {
                      LightsOn();
                    }
                    if(time>on && time>off && flag == 0)
                    {
                      LightsOn();
                      writeEEPROM(addr,4,1);
                    }
                    if(time<on && time> off && flag == 1);
                    {
                      writeEEPROM(addr,4,0);
                    }
}
}
void loop () {
     readEEPROM(addr,0);         
    onH=rec;               
    readEEPROM(addr,1);         
    onM=rec;               
    readEEPROM(addr,2);         
    offH=rec;
    readEEPROM(addr,3);       
    offM=rec;
    readEEPROM(addr,4);
    flag=rec;
   int time = hour()*10000 + minute()*100+second();
   int on = onH*10000 + onM*100;
   int off = offH*10000 + offM*100;

if (time == on)
{
  if(flag == false)
  {
   
  LightsOn();
  flag = true;
  writeEEPROM(addr,4,1);
  }
}

if (time==off)
{
if(flag==true)
{
 
  LightsOff();
  flag = false;
  writeEEPROM(addr,4,0);
}
}
}


One think that I'd like to ask.
If I keep this in setup, it works at boot only. But I'd like to put it in loop so it updates when I change the times from the LCD menu.
Is it too much for the processor? Also I will add the pump as well and the feeder (that's another story, should be easier).
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Sep 19, 2014, 02:32 pm
A couple of suggestions. First:
Code: [Select]
    readEEPROM(addr,0);         
    onH=rec;               

is silly. readEEPROM() should not be writing to a global variable. It should be returning a value, so you can:
Code: [Select]
   onH = readEEPROM(addr, 0);

Second:
Code: [Select]
                    if(time>on && time <off && flag == 1)
flag is a boolean. You should be comparing to true or false, not 1 or 0. The comparison is not needed, anyway. flag == true will result in true only if flag contains true, so the == true but is unnecessary. As far as comparing to false, use !flag rather than flag == false.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 19, 2014, 03:50 pm
Like this?

Code: [Select]

............................
void setup()
{
............................
    onH=readEEPROM(addr,0);                         
    onM=readEEPROM(addr,1);                           
    offH= readEEPROM(addr,2);           
    offM=readEEPROM(addr,3);   
    flag = readEEPROM(addr,4);
  int time = hour()*100 + minute();
  int on = onH*100 + onM;
  int off = offH*100 + offM;

if(on<off){
                    if(time>on && time <off && flag)
                      {
                        LightsOn();
                      }
                     if(time>on && time<off && !flag)
                      {
                        LightsOn();
                        writeEEPROM(addr,4,1);
                      }
                     if(time>on && time>off && flag)
                      {
                        writeEEPROM(addr,4,0);
                      }
                     if(time<on && time<off && flag)
                      {
                        writeEEPROM(addr,4,0);
                      }
}

if(on>off){
                    if(time>on && time>off && flag)
                    {
                       LightsOn();
                    }
                    if(time<on && time<off && flag)
                    {
                      LightsOn();
                    }
                    if(time>on && time>off && !flag)
                    {
                      LightsOn();
                      writeEEPROM(addr,4,1);
                    }
                    if(time<on && time> off && flag);
                    {
                      writeEEPROM(addr,4,0);
                    }
}
}
void loop () {
...............................
    onH= readEEPROM(addr,0);             
    onM= readEEPROM(addr,1);             
    offH=readEEPROM(addr,2);   
    offM=readEEPROM(addr,3);
    flag=readEEPROM(addr,4);
   int time = hour()*10000 + minute()*100+second();
   int on = onH*10000 + onM*100;
   int off = offH*10000 + offM*100;

if (time == on)
{
  if(!flag)
  {
  LightsOn();
  flag;
  writeEEPROM(addr,4,1);
  }
}
if (time==off)
{
if(flag)
{
  LightsOff();
  !flag;
  writeEEPROM(addr,4,0);
}
}
}

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Sep 19, 2014, 04:27 pm
Quote
Like this?

Assuming you've made the necessary changes to readEEPROM(), almost.

Code: [Select]
                    if(time>on && time <off && flag)
                      {
                        LightsOn();
                      }
                     if(time>on && time<off && !flag)
                      {
                        LightsOn();
                        writeEEPROM(addr,4,1);
                      }
                     if(time>on && time>off && flag)
                      {
                        writeEEPROM(addr,4,0);
                      }
                     if(time<on && time<off && flag)
                      {
                        writeEEPROM(addr,4,0);
                      }

I don't like compound ifs, if they can be avoided, and they can here,

Code: [Select]
if(time>on && time <off)
{
   if(flag)
  {
  }
  else
  {
  }
}
else if(...


Alternatively, decide if flag is the first filter, and then decide on an action based on time in the if(flag) body.

Code: [Select]
  flag;
does nothing.

Code: [Select]
  !flag;
does nothing.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 19, 2014, 06:25 pm
I got carried away with flag and !flag :)

Code: [Select]


if(on<off){
                    if(time>on && time <off){                 
                        if(flag)
                        {  LightsOn(); }                       
                                                             }
          else if(time>on && time<off){
                        if(!flag)
                        {     LightsOn();
                              writeEEPROM(addr,4,1);}
                                                           }
         else if(time>on && time>off){
                        if(flag)
                         {writeEEPROM(addr,4,0);}
                                                          }
        else if(time<on && time<off){
                      if(flag)
                      {writeEEPROM(addr,4,0);}
                                                        }
          }

if(on>off){
                    if(time>on && time>off){
                      if(flag)
                      {LightsOn();}
                                                            }                   
            else if(time<on && time<off){
                      if(flag)
                      {LightsOn();}
                                                            }
           else if(time>on && time>off){
                      if(!flag)
                      {LightsOn();
                      writeEEPROM(addr,4,1);}
                                                           }                   
          else if(time<on && time> off){
                      if(flag)
                      {writeEEPROM(addr,4,0);}
                                                          }
}



and

Code: [Select]
byte readEEPROM(int addr, unsigned int eeaddress)                //EEPROM read function
  {
  Wire.beginTransmission(addr);
  Wire.write((int)(eeaddress >> 8));
  Wire.write((int)(eeaddress & 0xFF));
  Wire.endTransmission();
  Wire.requestFrom(addr, 1);
  Wire.read();
  }
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Sep 19, 2014, 06:29 pm
Code: [Select]
byte readEEPROM(int addr, unsigned int eeaddress)                //EEPROM read function
  {
  Wire.beginTransmission(addr);
  Wire.write((int)(eeaddress >> 8));
  Wire.write((int)(eeaddress & 0xFF));
  Wire.endTransmission();
  Wire.requestFrom(addr, 1);
  Wire.read();
  }

A function that is designed to return a byte, but that doesn't have a return statement is pretty useless.

byte readEEPROM(int addr, unsigned int eeaddress)                //EEPROM read function
  {
  Wire.beginTransmission(addr);
  Wire.write((int)(eeaddress >> 8));
  Wire.write((int)(eeaddress & 0xFF));
  Wire.endTransmission();
  Wire.requestFrom(addr, 1);
  return Wire.read();
  }

You need to actually return the value read.

3 of your if blocks involve flag being true. One involves flag being false. It would be better to have
Code: [Select]
if(flag)
{
   // Pick which case, based on time...
}
else
{
   // Deal with the one false case
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 19, 2014, 08:25 pm
Yes, you are right.
Is this way better?
Is it bad if I insert that into loop?

Code: [Select]
if(on<off){
                 if(flag)
                {
                    if(time>on && time <off)                                        
                       {  LightsOn(); }
                   else if(time>on && time>off)                      
                       {writeEEPROM(addr,4,0);}
                   else if(time<on && time<off)
                     {writeEEPROM(addr,4,0);}
                }
                else
                {
                  if(time>on && time<off)
                       {LightsOn();
                        writeEEPROM(addr,4,1);}
                }
}

if(on>off){
                 if(flag)
                 {
                     if(time>on && time>off)
                     {LightsOn();}                    
             else if(time<on && time<off)
                     {LightsOn();}
             else if(time<on && time> off)
                     {writeEEPROM(addr,4,0);}
                 }
           else
               {
                if(time>on && time>off)
                     {LightsOn();
                     writeEEPROM(addr,4,1);}
               }
}


Also the read function now has return on the byte
Code: [Select]
byte readEEPROM(int addr, unsigned int eeaddress)                //EEPROM read function
 {
 Wire.beginTransmission(addr);
 Wire.write((int)(eeaddress >> 8));
 Wire.write((int)(eeaddress & 0xFF));
 Wire.endTransmission();
 Wire.requestFrom(addr, 1);
 return Wire.read();
 }
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Vaclav on Sep 19, 2014, 09:09 pm
I hope these remarks will be taken in spirit intended. Suggestions as posted in the original title.
First of all - it is plain crazy to build on thread of this length and age, Why?
I did not follow the last discussion post by post , but from my recent exposure to time ( lower case) related issues I would suggest always use "long"  for  time variables,  using "int" can and will create bugs.
Library Time puts most of the variables in "long"  anyway.
I think, personal opinion, using variable names "on" and "off"  for anything but byte is very poor choice.
I am not total fan of Hungarian notation(s) and lousy typist to boot, but few more characters in descriptive name  is better in long run.
After all, C will take up to 32 characters ( at lest it used to) and the  variable names don't take memory.
Cheers
Vaclav
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Sep 19, 2014, 09:17 pm
You are turning the lights on if the time is right, regardless of the value of flag.

You are writing a value to EEPROM that depends on the value in flag, regardless of what time it is.

Trying to combine the two actions in one set of if statements is crazy.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 19, 2014, 10:26 pm
Quote
I hope these remarks will be taken in spirit intended. Suggestions as posted in the original title.
First of all - it is plain crazy to build on thread of this length and age, Why?
I did not follow the last discussion post by post , but from my recent exposure to time ( lower case) related issues I would suggest always use "long"  for  time variables,  using "int" can and will create bugs.
Library Time puts most of the variables in "long"  anyway.
I think, personal opinion, using variable names "on" and "off"  for anything but byte is very poor choice.
I am not total fan of Hungarian notation(s) and lousy typist to boot, but few more characters in descriptive name  is better in long run.
After all, C will take up to 32 characters ( at lest it used to) and the  variable names don't take memory.
Cheers
Vaclav


I guess this is my 3rd of 4th arduino project, and certainly my most complex one. I really don't know how things are usually done in programming, I'm just getting my feet wet.
Also, the whole thing started as this was the place I found to be related to my earlier problems with timealarms library.

Code: [Select]
 
  onH= readEEPROM(addr,0);            
  onM= readEEPROM(addr,1);              
  offH= readEEPROM(addr,2);    
   offM= readEEPROM(addr,3);
   flag= readEEPROM(addr,4);

long  time = hour()*10000UL + minute()*100+second();
long on = onH*10000UL + onM*100;
long off = offH*10000UL + offM*100;


Quote
You are turning the lights on if the time is right, regardless of the value of flag.


Code: [Select]
if (time == on)
{
if(!flag)
 {
LightsOn();
flag=true;
writeEEPROM(addr,4,1);
 }
}

The lights go on only if the time is right and flag is 0. Same, the lights go off at a certain hour if time is right and flag is 1. If the flag is 1, the lights won't come on. Right?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Sep 19, 2014, 11:40 pm
Quote
The lights go on only if the time is right and flag is 0. Same, the lights go off at a certain hour if time is right and flag is 1. If the flag is 1, the lights won't come on. Right?

flag is a boolean. It is true or false, not 0 or 1.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Bob808 on Sep 20, 2014, 12:23 am
Yes I know that, it's quicker to type, I guess you get the idea. In program indeed it's better to write true or false always.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: joe4444 on Sep 25, 2014, 01:58 am
Hi again

Please could someone help me with just setting an alarm for a specific date and time.

I did ask this question a few weeks ago and thanks Pauls for the clock tip ..I did manage to trigger an event with the time library and the DS1307 library.
however I would like to use the timealarms library because it seems perfect for what I would like to do.
It seems like what Bob808 is chatting about and getting help with is similar to what I would like to achive with one exception and that's setting the trigger times for HMS (hour minute second) and DMY(day month year)

The timealarms library works great for HMS but how do you set an alarm for a specific date ?

At the moment I am just trying to get a few lights switching on and off at specific dates and times for example 2014/9/25 @ 01:38 AM.
Does a basic example for this specific request above exist ?

I would like to be able to :
1. Set a given device (assuming I assign each infrared light a device ID) for on and off at a specific time.
(this done by perhaps applying an alarm ID to match the device ID when the alarm is created.
2.Be able to delete/disable/reset and alarm once set.
(this would be grabbed from a list or possibly from EEPROM if stored there)
3. If the list of alarms is stored in EEPROM (assuming this is possible for multiple alarms, ow many can be stored in the arduino EEPROM.
Please forgive any coding issues or misconceptions as I am fairly new to Arduino's and was used to programming PIC's in basic as a hobbyist.
I have been reading through snippets of code and these forums and googling for weeks now and don't seem to be making much headway with this.

I hope some kind soul can help or guide me as I really would like to build on my successes with the Arduino and also be able to give back to the forum somehow.
I am sure that if I could get a basic example I would be able to make some headway albeit fumbling around in the dark.

Regards
joe444
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Sep 25, 2014, 08:49 am
Quote
At the moment I am just trying to get a few lights switching on and off at specific dates and times for example 2014/9/25 @ 01:38 AM.
Does a basic example for this specific request above exist ?

From the TimeAlarms readme
Quote
If you want to trigger once at a specified date and time you can use the trigger Once() method:
  Alarm. triggerOnce(time_t value,  explicitAlarm); // value specifies a date and time
(See the makeTime() method in the Time library to convert dates and times into time_t)




Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: joe4444 on Sep 26, 2014, 02:26 am
Hi all

Thanks UKHeliBob

This is exactly where I am battling
Quote
See the makeTime() method in the Time library to convert dates and times into time_t

I keep reading over the time library info and trying to find a clear simple example of create the time_t from the method mentioned.
I have have been reading over the the code in the forums for days now since my last posting :-(

Quote
void localTime(time_t *timep,byte *psec,byte *pmin,byte *phour,byte *pday,byte *pwday,byte *pmonth,byte *pyear);
    extracts time components from time_t. Note that year here is the desired year minus 1900
time_t sTime makeTime(byte sec, byte min, byte hour, byte day, byte month, int year );
    returns time_t from time components, note that year here is full four digit year.


My question/confusion so far:
1.How do I correctly initially set/assign the variables in order to  return the time_t from the time components?
In my code if I want to create a startTime is it a case of assigning each variable a value like this :
Code: [Select]
byte sec = 33;
byte min = 20;
byte hour = 13;
byte day = 26;
byte month = 09;
int year = 2014 

then
Code: [Select]
time_t makeTime(byte sec, byte min, byte hour, byte day, byte month, int year );

OR is it like this

Code: [Select]
tmElements_t stm;
  stm.Year = 2014 - 1970; 
  stm.Month = 09;
  stm.Day = 26;
  stm.Hour = 02;
  stm.Minute = 01;
  stm.Second = 00;
  Alarm.triggerOnce(makeTime(stm), OnceOnly) ;


Please excuse NOOB confusion.

I really am battling to make light of this and a little guidance please.

As always I look forward to any replies..

Regards
Joe
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: joe4444 on Sep 26, 2014, 03:28 am
YAY
I decided to bash around a bit more and ...
It looks like it's working :-)
Would still love some answers if possible on the last post though ;-)

Here's the code for anyone battling to create a ONCE-OFF alarm in other words with a specific date and time to start and a specific end time.
The most difficult hurdle for me was just to see how the time_t object is created and excatly where it slots in, and that took me two weeks of searching after my initial post here.
So I really do hope this helps some people.

I now have a few more questions:

1.
I would like to assign a start and end time to each device using its deviceID.
What would be the correct(or a nice)  way to assign both an start and end time to each single deviceID.
For example if I enter 465 into the serial monitor as the device ID and then run through collecting the start and end times for the device.
Since I am creating two time_t  object stm (start time) and etm (end time) , I was wondering how to have the device ID attach to each time_t object.
Some form of concatenation perhaps or is there a better/different method ?
I think something like stm465 and etm465 would be awesome ... ?
Any tips or comments please?

2.
How does once store the alarm ID's so yo can reference them later. (I remember seeing a post answered by PaulS somewhere in the last few days/weeks about this very same question but for the life of me I can't remember the topic to search on.

3.
If each alarm is stored in the Arduino UNO eeprom, how many alarms could be created and what byte size is taken up by each alarm ?

4.
From what I have been reading through the posts, is it correct to summize that each is destroyed after triggering ?

5.
Could or would somebody suggest some re-useable routine/code or steps to create a start and end alarm for each deviceID ?

Thanks a million for this library and to those people who have replied to my posts , I definitely found every single reply useful.

Kind regards

Joe

Code: [Select]
#include <Time.h>
#include <TimeAlarms.h>

void setup()
{
 Serial.begin(9600);
 setTime(2,38,30,26,9,14); // set time to Saturday 2:38:30am September 26 2014

tmElements_t stm; // start time values go here
 stm.Year = 2014 -1970;
 stm.Month = 9;
 stm.Day = 26;
 stm.Hour = 2;
 stm.Minute = 39;
 stm.Second = 0;
 Alarm.triggerOnce(makeTime(stm), OnceOnly) ;

tmElements_t etm; // end time values go here
 etm.Year = 2014 -1970;
 etm.Month = 9;
 etm.Day = 26;
 etm.Hour = 2;
 etm.Minute = 39;
 etm.Second = 30;
 Alarm.triggerOnce(makeTime(etm), OnceOnly) ;

}

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

// functions to be called when an alarm triggers:

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


Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Sep 26, 2014, 04:51 pm
Quote
1.
I would like to assign a start and end time to each device using its deviceID.
What would be the correct(or a nice)  way to assign both an start and end time to each single deviceID.
For example if I enter 465 into the serial monitor as the device ID and then run through collecting the start and end times for the device.

What device(s) are you referring to? The TimeAlarms class creates objects that are meant to model real alarm clocks. The ID of an alarm is assigned by the TimeAlarms class, not by you.

Quote
Since I am creating two time_t  object stm (start time) and etm (end time) , I was wondering how to have the device ID attach to each time_t object.

This question does not make sense without knowing what device(s) you are talking about.

Quote
2.
How does once store the alarm ID's so yo can reference them later. (I remember seeing a post answered by PaulS somewhere in the last few days/weeks about this very same question but for the life of me I can't remember the topic to search on.

In a variable (or array) of the proper type. Look at the TimeAlarms class to see what that type is.

Quote
3.
If each alarm is stored in the Arduino UNO eeprom, how many alarms could be created and what byte size is taken up by each alarm ?

They are not. You can experiment to determine how much your code size changes when you allow for more than the pre-defined number of alarms.

Quote
4.
From what I have been reading through the posts, is it correct to summize that each is destroyed after triggering ?

I don't think so. The source code is the definitive answer, though.

Quote
5.
Could or would somebody suggest some re-useable routine/code or steps to create a start and end alarm for each deviceID ?

Not until you explain what you mean by device ID.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: joe4444 on Sep 26, 2014, 08:15 pm
Hi all

@PaulS thanks a million for the reply

With regard to this question 3 in my earlier post concerning the EEPROM:
Quote
If each alarm is stored in the Arduino UNO eeprom, how many alarms could be created and what byte size is taken up by each alarm ?
.
I see the possible confusion there ..let me clear that up
I realize that each alarm is not strored in the EEPROM of the Arduino UNO , is it possible that they may be stored there ?
And thank you for the tip ....I will check how many bytes the code increases by after compiling with the addition of each new alarm. I just thought someone (like the creator of the library) might already know this.

Oh I see the possible confusion in terms of DEVICE ID as well .
DEVICE ID is a number attached to a light. So for example , light number 465 becomes DEVICE ID 465 and in code I guess would be
Code: [Select]
int DEVID
So if one wanted DEVID 465 to be on @ a fixed date and time
you could key in (via serial maybe) the DEVID (in this case 465) and then you could set the start time and end times and the necessary alarms(Start and End) would be created and eventually triggered.
Basically I would like to attach a single DEVID to a start and end time.
For example:
DEVID 465
start @ date/time
end @ date/time
DEVID 466
start@ date/time
end@ date/time
etc..

So to clear up the question,

How do I go about matching the DEVID to the alarmID or maybe assigning the DEVID as the alarmID ? OR get this to work.

As always any help and tips are hugely appreciated

Regards

Joe4444

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Sep 26, 2014, 08:39 pm
Quote
I will check how many bytes the code increases by after compiling with the addition of each new alarm. I just thought someone (like the creator of the library) might already know this.

From the TimeAlarms readme
Quote
Q: How many alarms can be created?
A: Up to six alarms can be scheduled. 
The number of alarms can be changed in the TimeAlarms header file (set by the constant dtNBR_ALARMS,
note that the RAM used equals dtNBR_ALARMS  * 11)
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: joe4444 on Sep 26, 2014, 08:46 pm
@ UKHeliBob

Thanks for the valuable tip.
I did see that in the readme and other several other posts and it seems many overlook it and I believe the max is 255 :-)

Kind regards
Joe4444
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Sep 27, 2014, 04:27 pm
Quote
I realize that each alarm is not strored in the EEPROM of the Arduino UNO , is it possible that they may be stored there ?

You could store a copy of the object in EEPROM. But, it makes no sense to do that. You can't recreate an object in memory just by reading some bytes from EEPROM. Now, storing and retreiving the time that an alarm is supposed to go off might make sense.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Sep 27, 2014, 04:33 pm
Quote
How do I go about matching the DEVID to the alarmID or maybe assigning the DEVID as the alarmID ? OR get this to work.

In the callback function, call:
Code: [Select]
  AlarmID_t getTriggeredAlarmId();          // returns the currently triggered  alarm id

Compare the returned value with the list of AlarmID_t's you saved when creating the alarms, and use the index to get the device ID from the corresponding list.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: joe4444 on Sep 27, 2014, 09:57 pm
So as per this page http://arduino.cc/en/Main/arduinoBoardUno the Arduino UNO R3:
EEPROM is 1KB (1024 Bytes)
SRAM is 2KB (2048 Bytes)

If dtNBR_ALARMS allowable values is 0 to 255 MAX and
the RAM value as per the document is alarms * 11
a simple calculation using defaults (6 alarms set)
is 6 X 11 = 66 RAM (is this bytes ?? )
As you can see the documentation is not clear here
Quote

Q: How many alarms can be created?
A: Up to six alarms can be scheduled.  
The number of alarms can be changed in the TimeAlarms header file (set by the constant dtNBR_ALARMS,
note that the RAM used equals dtNBR_ALARMS  * 11)

Is this is indeed bytes the 255 X 11 = 2805 bytes

So just using an example of 1024 Bytes :
1024/11 = 93 alarms

Now lets say I want a device (yes a device can be anything that requires and on and off pulse.. strecth your mind here ...anything !!)
and this so called device is assigned a device ID (let's call this devID)
and each devID is assigned a number (as one probably would if you have lots of devices) like 465 (in other words LED number 465).

So devID 465
has:
an ON/START alarm
and OFF/END alarm


So to sum up each devID has two alarms linked/associated with it

(NOTE*** if we stretch our mind a little then a single device could have multiple alarms and patterns and delay patterns associated.)

So assuming on two alarms for each instance of devID the equation renders the following if 0 counts:
0-255 (256) /2 = 128 devices Max

and according to documentation the ram requirement for this is
128*11 = 1408 Bytes (? if this is bytes)

To be on the close to the 1024KB arduino UNO limit then a safe figure is 93 alarms
BUT
This does not take possible extra flags into operation.
We might need to flag an alarm to see if it is valid now after a power failure, not so ?

Of course if you are using a separate EEPROM then you could grow the max devices to to the MAX of 255.

So as per this document :
http://arduino.cc/en/Tutorial/Memory
We see that :
Quote

If you have look-up tables or other large arrays, use the smallest data type necessary to store the values you need; for example, an int takes up two bytes, while a byte uses only one (but can store a smaller range of values).
If you don't need to modify the strings or data while your sketch is running, you can store them in flash (program) memory instead of SRAM; to do this, use the PROGMEM keyword.



So going back to one of my earlier questions:
Quote

1.
I would like to assign a start and end time to each device using its deviceID.
What would be the correct(or a nice)  way to assign both an start and end time to each

single deviceID.


What is the correct/nice/most appropriate C/C++/C#/Arduino way to do this this ?
And before you answer, I would appreciate a stub of code to explain this or pseudo code to get me started or a pointer to an example coupled with an explanation of this if you wouldn't mind please.
I am not asking you to write my code for me I just want to be able to understand how and what the best method is.

@PaulS

Thanks for the replies and the first reply does add clarity to my earlier questions where I seem to have added a little fuzz into devID and the actual alarm, but later also refers to directly after create and not just after triggering ?
I would like to know how to reference the alarms after creating them.

Quote

2.
How does once store the alarm ID's so you can reference them later. (I remember seeing a post

answered by PaulS somewhere in the last few days/weeks about this very same question but for

the life of me I can't remember the topic to search on.


Quote


You could store a copy of the object in EEPROM. But, it makes no sense to do that. You can't recreate an object in memory just by reading some bytes from EEPROM.

Yes I agree

So yes I need to store the start and end dates for each  alarm ID in EEPROM and link those to the devID 465.
I have seen examples storing data into the EEPROM and retrieving it on the guides.
But what do I to (or how do I )make the link between devID and Alarm ID ?


Quote

Now, storing and retrieving the time that an alarm is supposed to go off might make sense.


Assuming that devID has two alarms associated with it , how do you do this in one foul swoop ?

So in conclusion...

How do I go about creating the link between a devID (which already exists for example devID 465) and the alarm ID's (assuming there are two alarm ID's for each devID ?

Is it an array ?

If I create something like this as a start (and please forgive my programming mistakes):
Code: [Select]

byte devID[128] =
OR
int devID[128] =


This could/would store the devID to two alarm ID's which in turn may or may not be stored in EEPROM not so ?
So devID needs to equal 2 alarm ID's
How do I link each devID with each devID ?

Would I be totally off the mark by thinking along these lines ?:
Code: [Select]

int alarmID = 1;//col
int stenAlarm = 2;//row
int[][] myArray = new int[alarmID][sten_alarm];

 
// For every alarmID i, for every start end alarm visit every row J.
for (int i = 0; i < alarmID; i++) {
 for (int j = 0; j < stenAlarm; j++) {
   myArray[i][j] = 0;
 }
}


May work but how would I link the devID to the alarmID ?

Here's what I have in mind in pseudo code:

receive a devID (example here is 465)
create a start alarm, store it in arduino EEPROM and link this Alarm ID to the devID
create and end alarm, store it in arduino EEPROM and link this Alarm ID to the devID
Store each alarm time in EEPROM

I understand that devID should always link to two alarm ID's and each Alarm ID points to the time and date.

I also understand that devID 465 may point to Alarm ID 5 and 70.

So how do I keep this mapping correct ?

I also read that alarms can be reset or freed.

Please can somebody shed some light or assist me

Regards

JOE4444
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Sep 28, 2014, 02:06 am
Quote
As you can see the documentation is not clear here

It's clear to me. Memory usage is ALWAYS expressed in bytes.

Quote
To be on the close to the 1024KB arduino UNO limit then a safe figure is 93 alarms

There are no Arduinos with 1024 kilobytes of memory, of any kind.

Don't plan on using all of your memory on alarms. You also need to store device IDs and plenty of other stuff.

Quote
But what do I to (or how do I )make the link between devID and Alarm ID ?

Use two arrays. When an alarm goes off, get it's ID. Find that ID in the alarm ID array. The value in the correspond position of the other array is the device ID.

Quote
How do I link each devID with each devID ?

Pretty easy, really. What was your real question?

I'm thinking that you should have a struct, containing a device ID, two alarm IDs, and whatever other data you need - maybe a pin number or ?.

Quote
Would I be totally off the mark by thinking along these lines ?:

Absolutely. It makes not sense to dynamically define a statically sized array. And, this is NOT C#.

Quote
receive a devID (example here is 465)

From where?

Code: [Select]
create a start alarm, store it in arduino EEPROM and link this Alarm ID to the devID
Forget the notion of storing the Alarm object in EEPROM. Storing the alarm TIME makes sense. Storing the Alarm object does NOT.

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: joe4444 on Sep 28, 2014, 03:37 am
@PaulS

Quote
There are no Arduinos with 1024 kilobytes of memory, of any kind

Can you shed some light on this one ??
http://arduino.cc/en/Main/arduinoBoardUno (http://arduino.cc/en/Main/arduinoBoardUno)
As per the spec ...
Quote
Flash Memory   32 KB (ATmega328) of which 0.5 KB used by bootloader
SRAM   2 KB (ATmega328)
EEPROM   1 KB (ATmega328)


Quote
It's clear to me. Memory usage is ALWAYS expressed in bytes.

All clear ..at least some clarification to say the least!
Thanks

Quote
Use two arrays. When an alarm goes off, get it's ID. Find that ID in the alarm ID array. The value in the correspond position of the other array is the device ID.


Why when the alarm goes off ??
I don't think you understand that I would like to catch the ID when the alarm is created for the start alarm and then catch the alarm ID of the end alarm and somehow link that to to what have called call a (device ID) devID. (See earlier posts(s))
You have asked me what the device is..I have given clarification in my previous posts.
What is not still clear to you ?

Quote

Don't plan on using all of your memory on alarms. You also need to store device IDs and plenty of other stuff.

Yes agreed ..thanks again !
So if you have read my last post what would be a safe number of alarms to create considering that each device ID (devID) would require two alarms namely a start and end alarm ?

Quote

Use two arrays. When an alarm goes off, get it's ID. Find that ID in the alarm ID array. The value in the correspond position of the other array is the device ID.

Could you possibly elaborate here regarding the correspond position ?

Quote

How do I link each devID with each devID ?
Pretty easy, really. What was your real question?


I think a typo by me here ...sorry , it is meant to read as
How do I link each devID with each alarm ID ?
Does that help ?

Quote

I'm thinking that you should have a struct, containing a device ID, two alarm IDs, and whatever other data you need - maybe a pin number or ?.


AAH :-) thank you (I'm starting to see a little little light at last) , so this would allow me to enter and store the devID and start and end alarm ID's in the format they need to be in ?

Quote
Absolutely. It makes not sense to dynamically define a statically sized array. And, this is NOT C#

So a 2D array is not the better method then ?
And you're right , this is not C# (or processing) but this is hobbyist(not so sharp)
:-)

Quote
receive a devID (example here is 465)
From where?


At the moment serial is the easiest to test with  OR I can pre-populate the variable as devID 465 OR it can be keypad or from anywhere I suppose.
But right now it's from serial console...
Does that help ?

Quote

create a start alarm, store it in arduino EEPROM and link this Alarm ID to the devID

Forget the notion of storing the Alarm object in EEPROM. Storing the alarm TIME makes sense. Storing the Alarm object does NOT.]


OK EEPROM alarm object is a no no then ... TIME is what should be stored in the EEPROM  ..agreed !
And those times are the time from the startalarm object and the time from from the end time object.
Going back to the earlier post , each devID should have both a start and end time.
That means that devID 465 has two alarm OBEJCTS namely a startalarm OBJECT and an endalarm OBJECT and each OBECJT has a time attached.
So as i mentioned in the earlier post  :
Quote

So devID 465
has:
an ON/START alarm
and OFF/END alarm


So to sum up each devID has two alarms linked/associated with it



To be inline with your statement and naming convention I guess true and correct with the timealarms library then:
devID 465
has:
an ON/START alarm OBJECT which has a set time
and OFF/END alarm OBJECT which has a set time

To sum up, each devID has two alarms linked/associated with it.

So if I'm finally getting the logic right here, I need :
1.
Two arrays
alarmID[] and devID[]
BUT that's why I thought using a 2D array here because each devID has two alarm ID's
With a 2D array the reference would be something like devid465 and alarmID [12] and alarmID [13]
@PaulS
What did you have in mind here ?
2.
a Struct for devID and two alarmID OBJECTS and a pin  
@PaulS
What was your intention for the use of the struct exactly ? Is it so I can reference the devID and two alarmID's as a single object from one of the arrays ?


Look forward to your replies (and anyone elses too)

Thanks again

Kind regards
JOE4444




Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: bperrybap on Sep 28, 2014, 07:12 am

@PaulS
Quote
There are no Arduinos with 1024 kilobytes of memory, of any kind

Can you shed some light on this one ??
http://arduino.cc/en/Main/arduinoBoardUno (http://arduino.cc/en/Main/arduinoBoardUno)
As per the spec ...
Quote
Flash Memory   32 KB (ATmega328) of which 0.5 KB used by bootloader
SRAM   2 KB (ATmega328)



1 KB is not the same as 1024 kilobytes.
(Well not unless you do math like Verizon):  http://www.youtube.com/watch?v=zN9LZ3ojnxY (http://www.youtube.com/watch?v=zN9LZ3ojnxY)
Units matter.
1024 kilobytes is 1MB.


Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Sep 28, 2014, 02:31 pm
Quote
Why when the alarm goes off ??

You have 42 alarm clocks in your bedroom. Does it matter what they are for when they are all quiet? When one goes off, and wakes you up, does it matter which one needs to STFU?

Quote
I don't think you understand that I would like to catch the ID when the alarm is created for the start alarm and then catch the alarm ID of the end alarm and somehow link that to to what have called call a (device ID) devID. (See earlier posts(s))

I understand that. When you create the alarm, it tells you the alarm ID. The alarm hasn't a clue why you set it. That only matters to you.

Of course you need to record the alarm IDs when you create them. Since the alarm IDs have some relation to other things, you need to record that relationship when the alarms are created.

I assumed that you were asking about how to determine the device the alarm is for when the alarm goes activate. THAT is when it matters.

Quote
What was your intention for the use of the struct exactly ? Is it so I can reference the devID and two alarmID's as a single object from one of the arrays ?

Yes. It's still not clear what you intend to do when an alarm goes off. Looking through the array of structs to see if this alarm if the start alarm or the end alarm for the device at this position will let you determine the device. But, then what? Clearly (to me at least), the Arduino should actually do something when the alarm goes off. It should turn a pin on or off. It should display a message somewhere. It should do something.

The information needed to do whatever needs to be done could be stored in the struct, too, keeping all the related data together in one data structure.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: AdaptTech on Oct 16, 2014, 08:10 pm
I'm using Ubuntu 14.04 LTS and Arduino IDE 1.0.5, and while using the Time library I get this errors:

Quote

In file included from /home/adapttech/sketchbook/libraries/Time/DateStrings.cpp:11:0:
/home/adapttech/sketchbook/libraries/Time/DateStrings.cpp:41:22: error: variable 'monthNames_P' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
PGM_P monthNames_P[] PROGMEM =
                      ^
/home/adapttech/sketchbook/libraries/Time/DateStrings.cpp:58:20: error: variable 'dayNames_P' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
PGM_P dayNames_P[] PROGMEM = { dayStr0,dayStr1,dayStr2,dayStr3,dayStr4,dayStr5,dayStr6,dayStr7};
                    ^
/home/adapttech/sketchbook/libraries/Time/DateStrings.cpp: In function 'const char* monthStr(uint8_t)':
/home/adapttech/sketchbook/libraries/Time/DateStrings.cpp:63:35: error: new declaration 'const char* monthStr(uint8_t)'
const char* monthStr(uint8_t month)
                                   ^
In file included from /home/adapttech/sketchbook/libraries/Time/DateStrings.cpp:21:0:
/home/adapttech/sketchbook/libraries/Time/Time.h:127:7: error: ambiguates old declaration 'char* monthStr(uint8_t)'
char* monthStr(uint8_t month);
       ^
/home/adapttech/sketchbook/libraries/Time/DateStrings.cpp: In function 'const char* monthShortStr(uint8_t)':
/home/adapttech/sketchbook/libraries/Time/DateStrings.cpp:69:40: error: new declaration 'const char* monthShortStr(uint8_t)'
const char* monthShortStr(uint8_t month)
                                        ^
In file included from /home/adapttech/sketchbook/libraries/Time/DateStrings.cpp:21:0:
/home/adapttech/sketchbook/libraries/Time/Time.h:129:7: error: ambiguates old declaration 'char* monthShortStr(uint8_t)'
char* monthShortStr(uint8_t month);
       ^
/home/adapttech/sketchbook/libraries/Time/DateStrings.cpp: In function 'const char* dayStr(uint8_t)':
/home/adapttech/sketchbook/libraries/Time/DateStrings.cpp:77:31: error: new declaration 'const char* dayStr(uint8_t)'
const char* dayStr(uint8_t day)
                               ^
In file included from /home/adapttech/sketchbook/libraries/Time/DateStrings.cpp:21:0:
/home/adapttech/sketchbook/libraries/Time/Time.h:128:7: error: ambiguates old declaration 'char* dayStr(uint8_t)'
char* dayStr(uint8_t day);
       ^
/home/adapttech/sketchbook/libraries/Time/DateStrings.cpp: In function 'const char* dayShortStr(uint8_t)':
/home/adapttech/sketchbook/libraries/Time/DateStrings.cpp:83:36: error: new declaration 'const char* dayShortStr(uint8_t)'
const char* dayShortStr(uint8_t day)
                                    ^
In file included from /home/adapttech/sketchbook/libraries/Time/DateStrings.cpp:21:0:
/home/adapttech/sketchbook/libraries/Time/Time.h:130:7: error: ambiguates old declaration 'char* dayShortStr(uint8_t)'
char* dayShortStr(uint8_t day);




I know for sure my code is alright (this compiles perfectly on Windows), and I've been looking around for answer in the Internet over a week.  Everybody seems to have a suggestion to downgrade gcc-avr, and some other people talk about manually changing the TimeStrings.cpp file.   All of these suggestions are dated a while ago, so, is there any new way to treat this problem?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: bperrybap on Oct 17, 2014, 12:27 am

I know for sure my code is alright (this compiles perfectly on Windows), ...

Not so fast.
Just because it compiles does not mean it is "alright".
The proprietary AVR libC progmem kludge macros that are used to put const data in flash
could be used incorrectly and still work with the older versions of the compiler.
My guess is that you are using a newer version of the compiler on Ubuntu than on Windows.
The newer version of the compiler no longer accepts many of the incorrect declarations
that were being used.
The good news is that if the declarations are done correctly, it works on the newer
version of the compiler as well as older versions of the compiler.

I have no idea which version of the Time library you are using (there are several floating around out there)
or where you got it but it is not properly declaring the progmem data.
While it "works" on older compilers it will not work on the newer compiler.
These incorrect/bad declarations have been being used for quite some time and there are MANY other
libraries that are having issues.
Even the examples for how to use progmem on the Arduino site
are wrong which adds to the problems.
I contacted Michael (the original author) a while back about this.
He updated the library with fixes for this, but you apparently don't have a version with those fixes.
It also appears that the zip file on Pauls Teensy site also does not have these fixes.

The declarations in DateString.cpp you have are:
Code: [Select]

PGM_P  monthNames_P[] PROGMEM =

Code: [Select]
PGM_P  dayNames_P[] PROGMEM =

And they need to be:
Code: [Select]
PGM_P const monthNames_P[] PROGMEM =
Code: [Select]

PGM_P const dayNames_P[] PROGMEM =


You will need to edit the file to correct these declarations.
Once corrected, it should work on the new and the old compilers.

--- bill
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: AdaptTech on Oct 17, 2014, 01:18 pm
Hello Bill,

Thank you for your answer.

I did what you told me, but now this is what I get:



This is my DateStrings.cpp file:

Code: [Select]

/* DateStrings.cpp
* Definitions for date strings for use with the Time library
*
* No memory is consumed in the sketch if your code does not call any of the string methods
* You can change the text of the strings, make sure the short strings are each exactly 3 characters
* the long strings can be any length up to the constant dt_MAX_STRING_LEN defined in Time.h
*
*/

#if defined(__AVR__)
#include <avr/pgmspace.h>
#else
// for compatiblity with Arduino Due and Teensy 3.0 and maybe others?
#define PROGMEM
#define PGM_P  const char *
#define pgm_read_byte(addr) (*(const unsigned char *)(addr))
#define pgm_read_word(addr) (*(const unsigned char **)(addr))
#define strcpy_P(dest, src) strcpy((dest), (src))
#endif
#include <string.h> // for strcpy_P or strcpy
#include "Time.h"

// the short strings for each day or month must be exactly dt_SHORT_STR_LEN
#define dt_SHORT_STR_LEN  3 // the length of short strings

static char buffer[dt_MAX_STRING_LEN+1];  // must be big enough for longest string and the terminating null

const char monthStr1[] PROGMEM = "January";
const char monthStr2[] PROGMEM = "February";
const char monthStr3[] PROGMEM = "March";
const char monthStr4[] PROGMEM = "April";
const char monthStr5[] PROGMEM = "May";
const char monthStr6[] PROGMEM = "June";
const char monthStr7[] PROGMEM = "July";
const char monthStr8[] PROGMEM = "August";
const char monthStr9[] PROGMEM = "September";
const char monthStr10[] PROGMEM = "October";
const char monthStr11[] PROGMEM = "November";
const char monthStr12[] PROGMEM = "December";

PGM_P const monthNames_P[] PROGMEM =
{
    "",monthStr1,monthStr2,monthStr3,monthStr4,monthStr5,monthStr6,
monthStr7,monthStr8,monthStr9,monthStr10,monthStr11,monthStr12
};

const char monthShortNames_P[] PROGMEM = "ErrJanFebMarAprMayJunJulAugSepOctNovDec";

const char dayStr0[] PROGMEM = "Err";
const char dayStr1[] PROGMEM = "Sunday";
const char dayStr2[] PROGMEM = "Monday";
const char dayStr3[] PROGMEM = "Tuesday";
const char dayStr4[] PROGMEM = "Wednesday";
const char dayStr5[] PROGMEM = "Thursday";
const char dayStr6[] PROGMEM = "Friday";
const char dayStr7[] PROGMEM = "Saturday";

PGM_P const dayNames_P[] PROGMEM = { dayStr0,dayStr1,dayStr2,dayStr3,dayStr4,dayStr5,dayStr6,dayStr7};
char const dayShortNames_P[] PROGMEM = "ErrSunMonTueWedThrFriSat";

/* functions to return date strings */

char* monthStr(uint8_t month)
{
    strcpy_P(buffer, (PGM_P)pgm_read_word(&(monthNames_P[month])));
return buffer;
}

char* monthShortStr(uint8_t month)
{
   for (int i=0; i < dt_SHORT_STR_LEN; i++)     
      buffer[i] = pgm_read_byte(&(monthShortNames_P[i+ (month*dt_SHORT_STR_LEN)])); 
   buffer[dt_SHORT_STR_LEN] = 0;
   return buffer;
}

char* dayStr(uint8_t day)
{
   strcpy_P(buffer, (PGM_P)pgm_read_word(&(dayNames_P[day])));
   return buffer;
}

char* dayShortStr(uint8_t day)
{
   uint8_t index = day*dt_SHORT_STR_LEN;
   for (int i=0; i < dt_SHORT_STR_LEN; i++)     
      buffer[i] = pgm_read_byte(&(dayShortNames_P[index + i])); 
   buffer[dt_SHORT_STR_LEN] = 0;
   return buffer;
}


After running with this file, I get the following errors:

Quote


In file included from /home/adapttech/sketchbook/libraries/Time/DateStrings(fresh original).cpp:11:0:
/home/adapttech/sketchbook/libraries/Time/DateStrings(fresh original).cpp:41:22: error: variable 'monthNames_P' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
PGM_P monthNames_P[] PROGMEM =
                      ^
/home/adapttech/sketchbook/libraries/Time/DateStrings(fresh original).cpp:58:20: error: variable 'dayNames_P' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
PGM_P dayNames_P[] PROGMEM = { dayStr0,dayStr1,dayStr2,dayStr3,dayStr4,dayStr5,dayStr6,dayStr7};
                    ^
/home/adapttech/sketchbook/libraries/Time/DateStrings(fresh original).cpp:59:24: error: variable 'dayShortNames_P' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
char dayShortNames_P[] PROGMEM = "ErrSunMonTueWedThrFriSat";
                        ^
[\quote]

It seems I still have something wrong with the declarations.  I downloaded the [/b]Time[/b] library from here: http://www.pjrc.com/teensy/td_libs_Time.html

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: AdaptTech on Oct 17, 2014, 01:27 pm
Hello all,

It seems I have finally found the problem (special thanks to Bill for pointing me in the right direction).

The latest code for the StringNames.cpp file (as of the day of this post)  is available here: https://github.com/PaulStoffregen/Time/blob/master/DateStrings.cpp

The changes are:

Code: [Select]
const PROGMEM char * const PROGMEM dayNames_P[] =

And you need to remover all files named somewhat like `StringNames` from the`Time` folder (I left one name "Stringames (fresh original").cpp) .

Thanks a lot guys!
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: bperrybap on Oct 17, 2014, 04:31 pm
AdapTech,
Any time you mix files and changes from different libraries there can be issues.
The modification I gave was not quite enough to fix the files you had, there was one
more line that needed to be fixed.
As far as grabbing files from the git hub repo, it is best to grab all the files
from the master trunk or at least verify that there are no additional updates
to ensure you get all the files as a complete snapshot.

Are you perhaps using DUE / Teensy 3 ?

I don't fully agree with the way Paul has mapped the PROGMEM stuff and the declarations in that file.
Paul and I have discussed the PROGMEM mapping defines and its related issues in the past.
Some of the declarations in that file are mixing & matching their use of the progmem macros so
their use is a bit inconsistent.
While it might work for both AVR and ARM, there are few declarations that inconsistent.
With this type of stuff, depending on how it is used in declarations, it can end up using
additional RAM.
While it looks like it should work in this case at least for the non AVR processors,
I have not tested / verified that the way they have done it works on all the processors and
ensures no additional RAM overhead.

--- bill
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: AdaptTech on Oct 17, 2014, 05:24 pm
Hi Bill,

No, I'm using the Arduino UNO.

I hope this could be fix in a later version :).

Thanks again!
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: glitchsniffer on Jan 13, 2015, 08:49 am
Ok, so as far as I can tell I have everything working correctly, except changing the time on the alarm.  I can change the time, read out the time and everything works fire.  Except that it doesn't work until I reset the Arduino.  After I do the Alarm.write, I do an Alarm.disable, but it doesn't change the time till the next time it triggers.  Here are my code for writing the alarm after I change it.

Code: [Select]
Alarm.write(AlarmIDOn_0, AlarmHMS(AlarmHourOn_0, AlarmMinOn_0, 0));
Alarm.enable(AlarmIDOn_0);


When I do a Alarm.read right after this, It reads out the correct time, it just doesn't trigger the next time.

Is there anything I'm missing here?  I'm just trying to turn a light on and off on a timer.

Any help would be appreciated.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Clemens on Jan 13, 2015, 03:26 pm
I read this old thread (read only) about the TimeAlarm lib http://forum.arduino.cc/index.php?topic=37693.0 and want to come back to the third posting. ;-)

Quote
Can arduino be put to sleep ...
I phrased it a bit more in detail in this post http://forum.arduino.cc/index.php?topic=291983.0

So the question is still how can we bring the Arduino in sleep as long we are waiting for the next triggered event?

Narcoleptic has a kind of timekeeping function, so it should be possible in theory, but my knowledge about lib programming is not so waterproof to do it on my own. Can someone jump in?

For the meantime this workaround could be possible:
- In case you want to sleep the Arduino check in which time intervall the next event will be,
- sent the Arduino to sleep via Narcoleptic for this intervall minus some ms
- after waking up adjust the time via the millis Narcoleptic has logged and let TimeAlarm work.

But is there a function when the next event is scheduled? E.g. next event in 15678 Sekunds or today 11:15:00 ??
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Clemens on Jan 13, 2015, 11:51 pm
But is there a function when the next event is scheduled? E.g. next event in 15678 Sekunds or today 11:15:00 ??
Seems that Alarm.getNextTrigger() does the job. It returns the next trigger as  time_t.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: gchico63 on Jan 14, 2015, 10:36 pm
I need some help using the time library.  I want to create a time_t value from the component (hr,min,sec,day,month,yr) pieces.  Similar to how the setTime() works, except I want to store my specified time in a variable to be used in some timer calculations.  I tried to use tmElements_t variable types with no luck.  Didn't even recognize it as a variable type. Same with the makeTime function.  Are these still supported in the newest time library?  Can someone show me an example of how I could take (hr,min,sec,day,month,yr) as an input to calculate a time_t?   I'm new to this, but yes I did remember to type #include <Time.h>  Thanks in advance for any help.


Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Clemens on Jan 17, 2015, 01:38 pm
see makeTime http://www.pjrc.com/teensy/td_libs_Time.html

Code: [Select]

#include <Time.h>
tmElements_t tm;

void setup()
{
  Serial.begin(9600);
  setTime(8,29,0,1,1,11); // set time to Saturday 8:29:00am Jan 1 2011
 
  tm.Year = 2011 - 1970;  // this would be year 2013
  tm.Month = 1;
  tm.Day = 1;
  tm.Hour = 8;
  tm.Minute = 29;
  tm.Second = 0;
}

void  loop(){ 
  Serial.println (now());
  delay(1000);
  Serial.print("Make: ");
  Serial.println(makeTime(tm));
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Dr_Quark on Jan 20, 2015, 04:22 pm
[SOLVED--see next post]

I'm getting the wrong year when I setTime(23,0,0,0,0,0) and then print(year()). My print output is "1999" instead of 1970. See the more detailed question I posted at:

http://forum.arduino.cc/index.php?topic=293736.0

When I changed it to setTime(23,0,0,0,0,19), the year printed as "2018". I let the clock run for 3 hours, so it rolled into the next day and now (at clock time of 02:13:00) the year is "2019" as the clock has rolled into the next day.

I'm going to write some code to watch the time functions work over 24 hours and see if I can spot the problem, eg, what are each of these doing?

now(), hour(), day(), month(), year()
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Dr_Quark on Jan 20, 2015, 05:34 pm
Oops, got it. I was assuming that setTime(hr, min, sec, day, month, year) was using offsets from zero, like zero indexing. So setting day, month or year to 0 causes the error.

I checked setTime(0) and that works as expected. 1970 is, indeed, the base year. The function setTime(0,0,0,1,1,1970) is essentially setTime(0).
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Erik_SR on Jan 26, 2015, 10:48 am
Hi,

I use the TimeAlarms library to execute alarms on times that are called in an array. However, the alarms go off at the same time everyday. I have a hunch that the problem is the difference between alarmOnce and alarmRepeat, but I can't figure out whats wrong. Could you help?

This is my code:

Code: [Select]

#include <Time.h>
#include <TimeAlarms.h>

int x;    //Showing Number
int h;    //Spot ON time - hour
int m;    //Spot ON time - minute

int e;    //int for time outside 60 minutes --> hour +1
int t;    //int for time outside 60 minutes --> hour +1
int z;    //int for time outside 60 minutes --> hour -1

int f;    //Spot off time - minute
int o;    //Spot warm up time - minute
int c;    //Shutter close time - minute


//Contact Channel set-up
int SpotOn = 4;          //CONTACT 1 -- RED Wire
int ShutterOpen = 5;     //CONTACT 2 -- GREEN Wire
int ShutterClose = 6;    //CONTACT 3 -- BLUE Wire
int SpotOff = 7;         //CONTACT 4 -- YELLOW Wire

int i;
int j;
int k;
int l;


int hourArray[] =   {17, 18, 19, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 18, 17, 18, 17, 18, 18, 18, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19, 18, 18, 19, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 20, 19, 20, 20, 19, 20, 20, 20, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 20, 21, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 21, 21, 21, 22, 22, 21, 22, 21, 22, 22, 21, 22, 21, 22, 22, 22, 22, 22, 22, 21, 22, 22, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 20, 20, 21, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 19, 19, 20, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 18, 18, 19, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17};

int minuteArray[] = {36, 31, 33, 30, 32, 42, 35, 31, 32, 34, 49, 38, 38, 42, 48, 44, 45, 46, 0, 52, 4, 57, 9, 9, 8, 54, 10, 4, 20, 18, 12, 10, 26, 29, 28, 22, 15, 33, 25, 36, 29, 41, 43, 32, 47, 50, 55, 51, 42, 47, 45, 43, 44, 52, 3, 48, 53, 0, 56, 4, 5, 15, 16, 22, 13, 15, 32, 15, 19, 27, 24, 29, 39, 30, 24, 31, 24, 49, 29, 54, 43, 46, 50, 37, 53, 48, 5, 50, 2, 5, 56, 2, 12, 11, 59, 16, 15, 9, 25, 9, 10, 24, 19, 23, 16, 21, 24, 29, 38, 27, 37, 40, 36, 37, 54, 54, 45, 58, 59, 0, 55, 2, 56, 59, 57, 3, 6, 7, 3, 5, 17, 10, 8, 21, 21, 27, 30, 19, 34, 26, 23, 35, 30, 35, 32, 37, 38, 42, 39, 40, 43, 42, 49, 51, 52, 50, 49, 57, 57, 53, 55, 57, 55, 55, 3, 1, 57, 56, 59, 4, 5, 58, 6, 59, 7, 1, 58, 2, 58, 4, 3, 5, 1, 3, 2, 55, 1, 2, 56, 54, 55, 50, 59, 49, 52, 48, 47, 50, 47, 43, 49, 38, 46, 33, 37, 42, 34, 26, 31, 27, 22, 24, 18, 12, 12, 18, 24, 7, 11, 7, 12, 1, 0, 1, 5, 56, 59, 4, 43, 49, 40, 47, 40, 39, 40, 45, 27, 29, 18, 34, 28, 19, 17, 24, 18, 8, 10, 13, 12, 51, 54, 5, 50, 59, 50, 52, 38, 41, 45, 28, 29, 34, 44, 41, 19, 20, 10, 19, 7, 12, 26, 3, 17, 1, 0, 8, 8, 43, 42, 3, 46, 51, 51, 51, 53, 36, 31, 32, 31, 40, 31, 34, 30, 32, 27, 28, 6, 11, 1, 3, 1, 12, 11, 3, 0, 10, 0, 58, 42, 55, 56, 57, 36, 38, 36, 37, 45, 30, 30, 46, 46, 29, 42, 24, 35, 26, 27, 34, 26, 19, 21, 21, 31, 27, 19, 18, 22, 28, 14, 19, 18, 16, 10, 23, 11, 27, 18, 13, 22, 12, 21, 17, 27, 16, 14, 23, 26, 23, 23, 29, 27, 28, 17, 31, 17};


void setup() {
  // initialize serial and wait for port to open:
  Serial.begin(9600);

  //setting the digital pins to OUTPUT signal
  pinMode(SpotOn, OUTPUT);
  pinMode(ShutterOpen, OUTPUT);
  pinMode(ShutterClose, OUTPUT);
  pinMode(SpotOff, OUTPUT);

  //----------------------------------------------------------------------------------------------
  //THESE NEED TO BE ADJUSTED ACCORDIDNG TO CURRENT TIME

  x = 0;                                   // set to showing number

  setTime(17, 17, 26, 2, 1, 15);             // set time to (hours, minutes, seconds, days, months, years)
  //----------------------------------------------------------------------------------------------


}


void loop() {
  // these lines reset the pins to 0

  analogWrite(SpotOn, 0);
  analogWrite(ShutterOpen, 0);
  analogWrite(ShutterClose, 0);
  analogWrite(SpotOff, 0);

  h = hourArray[x];
  m = minuteArray[x];


  e = h;  //setting the end time hour to a different scope since it might fall in a different hour depending on the showing
  t = h;
  z = h;

  o = m - 8;       //the 8 min delay to heat up the spot
  c = m + 8;       //the 8 min showing
  f = c + 1;       //one minute after shutter closes spot turns off




  if ( c >= 60 )    //if the minutes become more than 60, which might happen with the closing times, this will adjust the hour and minutes to their proper stat
  {
    c = c - 60;
    e = e + 1;
  }

  if ( f >= 60 )
  {
    f = f - 60;
    t = t + 1;
  }

  if (o < 0)
  { o = o + 60;
    z = z - 1;
  }

/*
  Alarm.alarmRepeat(z, o, 0, LampON);      //The alarms starting their respective loops to turn ON the spot
  Alarm.alarmRepeat(h, m, 0, FadeIN);      //Open the shutter
  Alarm.alarmRepeat(e, c, 0, FadeOUT);     //Close the shutter
  Alarm.alarmRepeat(t, f, 0, LampOFF);     //Turn OFF the spot
*/


    Alarm.alarmOnce(17, z, o, LampON);        //uncomment for test run with seconds rather than minutes
    Alarm.alarmOnce(17, h, m, FadeIN);        //set time to 17, 17, 0 and x to 0
    Alarm.alarmOnce(17, e, c, FadeOUT);
    Alarm.alarmOnce(17, t, f, LampOFF);

  Alarm.delay(1000);
  h = hourArray[x];
  m = minuteArray[x];

}

void printDigits(int digits)
{
  Serial.print(":");
  if (digits < 10) {
    Serial.print('0');
  }
  Serial.print(digits);
}



void LampON() {      // This loop is triggered by the alarm
  analogWrite(SpotOn, 255);
  Alarm.delay(0);
}



void FadeIN() {
  analogWrite(ShutterOpen, 255);
  Alarm.delay(0);
}


void FadeOUT() {
  analogWrite(ShutterClose, 255);
   Alarm.delay(0);
}


void LampOFF() {
  analogWrite(SpotOff, 255);  //Turning off the contacts to drop below 2V again to reset them
  delay(25);
  analogWrite(SpotOn, 0);
  analogWrite(ShutterOpen, 0);
  analogWrite(ShutterClose, 0);
  analogWrite(SpotOff, 0);

  x ++;                      // Counting on to the next showing day
  if ( x == 364 ) {
    x = 0;
  }

  h = hourArray[x];    //array is only called again to print next showing time correctly
  m = minuteArray[x];

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Jan 26, 2015, 12:27 pm
Why does the program constantly keep setting up new alarms based on the current time ?  It seems to do this each time through loop().

What is it that you are trying to do ?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Erik_SR on Jan 26, 2015, 02:55 pm
Every day the alarmtrigger should execute at a different time. These times come from the long array. After every time a alarmtrigger was executed, new times for the day after are generated (x++)
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Jan 26, 2015, 03:52 pm
Surely what you should be doing is to calculate the time for the next alarm and setting it in the code triggered by the alarmOnce rather than doing it in the loop() function.

As far as I can see at the moment you are setting 4 new alarms, or trying to, each time through loop().
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Erik_SR on Jan 26, 2015, 05:10 pm
I'm not sure if I understand you but is this what you mean?

Code: [Select]

void setup(){
time = array[x];
}

void loop() {
Alarm.alarmOnce(time, lampOn);
Alarm.delay(1000);

}

void lampOn(){
do something;
time = newTime;
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Jan 26, 2015, 05:37 pm
Yes.  The do
Code: [Select]
something; would set the alarm for the next time.

Another question.  Why are the hour and minute arrays ints when the values would fit in a byte ?  Those arrays are big and you need to save every byte possible.  At the moment they are using a total of over 1400 bytes which could also cause problems depending on which Arduino you are running the program on.

As a matter of interest what is it that you are photographing at such precise times over the period of what looks like a year ?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Erik_SR on Jan 27, 2015, 08:58 am
Thank you for the help so far! I am using an Arduino Mega so the file size is not a problem (it was indeed almost a problem for the Uno). The Arduino triggers a DMX signal that powers a huge..let's call it a bat-light (still kinda secret) at a certain time throughout the year.

As far as the code goes. I still can't manage it to work :(. This is a simpler version in which I tried to use your tips. It runs once or twice and then stops.

Code: [Select]

#include <Time.h>
#include <TimeAlarms.h>

int x;    //Showing Number
int h;    //Spot ON time - hour
int m;    //Spot ON time - minute
int mn;


int o = 1;    //Spot warm up time - minute
int c = 9;    //Shutter close time - minute
int f = 10;    //Spot off time - minute

//Contact Channel set-up
int SpotOn;          //CONTACT 1 -- RED Wire
int ShutterOpen;     //CONTACT 2 -- GREEN Wire
int ShutterClose;    //CONTACT 3 -- BLUE Wire
int SpotOff;         //CONTACT 4 -- YELLOW Wire


int minuteArray[] = {5, 20, 40, 30, 32, 42, 35, 31, 32, 34, 49, 38, 38, 42, 48, 44, 45, 46, 0, 52, 4, 57, 9, 9, 8, 54, 10, 4, 20, 18, 12, 10, 26, 29, 28, 22, 15, 33, 25, 36, 29, 41, 43, 32, 47, 50, 55, 51, 42, 47, 45, 43, 44, 52, 3, 48, 53, 0, 56, 4, 5, 15, 16, 22, 13, 15, 32, 15, 19, 27, 24, 29, 39, 30, 24, 31, 24, 49, 29, 54, 43, 46, 50, 37, 53, 48, 5, 50, 2, 5, 56, 2, 12, 11, 59, 16, 15, 9, 25, 9, 10, 24, 19, 23, 16, 21, 24, 29, 38, 27, 37, 40, 36, 37, 54, 54, 45, 58, 59, 0, 55, 2, 56, 59, 57, 3, 6, 7, 3, 5, 17, 10, 8, 21, 21, 27, 30, 19, 34, 26, 23, 35, 30, 35, 32, 37, 38, 42, 39, 40, 43, 42, 49, 51, 52, 50, 49, 57, 57, 53, 55, 57, 55, 55, 3, 1, 57, 56, 59, 4, 5, 58, 6, 59, 7, 1, 58, 2, 58, 4, 3, 5, 1, 3, 2, 55, 1, 2, 56, 54, 55, 50, 59, 49, 52, 48, 47, 50, 47, 43, 49, 38, 46, 33, 37, 42, 34, 26, 31, 27, 22, 24, 18, 12, 12, 18, 24, 7, 11, 7, 12, 1, 0, 1, 5, 56, 59, 4, 43, 49, 40, 47, 40, 39, 40, 45, 27, 29, 18, 34, 28, 19, 17, 24, 18, 8, 10, 13, 12, 51, 54, 5, 50, 59, 50, 52, 38, 41, 45, 28, 29, 34, 44, 41, 19, 20, 10, 19, 7, 12, 26, 3, 17, 1, 0, 8, 8, 43, 42, 3, 46, 51, 51, 51, 53, 36, 31, 32, 31, 40, 31, 34, 30, 32, 27, 28, 6, 11, 1, 3, 1, 12, 11, 3, 0, 10, 0, 58, 42, 55, 56, 57, 36, 38, 36, 37, 45, 30, 30, 46, 46, 29, 42, 24, 35, 26, 27, 34, 26, 19, 21, 21, 31, 27, 19, 18, 22, 28, 14, 19, 18, 16, 10, 23, 11, 27, 18, 13, 22, 12, 21, 17, 27, 16, 14, 23, 26, 23, 23, 29, 27, 28, 17, 31, 17};


void setup() {
  // initialize serial and wait for port to open:
  Serial.begin(9600);

  //----------------------------------------------------------------------------------------------
  //THESE NEED TO BE ADJUSTED ACCORDIDNG TO CURRENT TIME

  x = 0;                                   // set to showing number

  setTime(17, 17, 0, 2, 1, 15);             // set time to (hours, minutes, seconds, days, months, years)
  //----------------------------------------------------------------------------------------------

  m = minuteArray[x];
  mn = minuteArray[x+1];


}


void loop() {
 
  Alarm.alarmOnce(17, 17, o, LampON);        //uncomment for test run with seconds rather than minutes
  Alarm.alarmOnce(17, 17, m, FadeIN);        //set time to 17, 17, 0 and x to 0
  Alarm.alarmOnce(17, 17, c, FadeOUT);
  Alarm.alarmOnce(17, 17, f, LampOFF);

  Alarm.delay(1000);
 
}


void printDigits(int digits)
{
  Serial.print(":");
  if (digits < 10) {
    Serial.print('0');
  }
  Serial.print(digits);
}



void LampON() {      // This loop is triggered by the alarm
  Serial.println(" ");
  Serial.println("------------------------------");
  Serial.println("Start Showing, lamp preheats");

  Serial.print(x);
  Serial.print("\t");
  Serial.println("  Current Showing number");

  Serial.print(day());
  Serial.print("-");
  Serial.print(month());
  Serial.print("-");
  Serial.print(year());
  Serial.println(" Current Showing date");

  Serial.print(":");
  Serial.print(o);
  Serial.print("\t");
  Serial.println("< Current time: Spot warm-up");

  Serial.print(":");
  Serial.print(m);
  Serial.print("\t");
  Serial.println("  Planned time showing start");

  Serial.print(":");
  Serial.print(c);
  Serial.print("\t");
  Serial.println("  Planned time showing stop");

  Serial.print(":");
  Serial.print(f);
  Serial.print("\t");
  Serial.println("  Planned time spot off");


  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print("\t");
  Serial.println("  Computer time");
 
  o = mn - 4;       //the 8 min delay to heat up the spot
 }



void FadeIN() {
  Serial.println("--");
  Serial.println("Lamp fades in");
  Serial.print(":");
  Serial.print(m);
  Serial.print("\t");
  Serial.println("< Time fade-in");
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print("\t");
  Serial.println("  Computer time");
 }


void FadeOUT() {
  Serial.println("--");
  Serial.println("Lamp fades out");
  Serial.print(":");
  Serial.print(c);
  Serial.print("\t");
  Serial.println("< Time fade-out");
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print("\t");
  Serial.println("  Computer time");
  c = mn + 4;       //the 8 min showing
}


void LampOFF() {
  Serial.println("--");
  Serial.println("Lamp off, showing ends");
  Serial.print(":");
  Serial.print(f);
  Serial.print("\t");
  Serial.println("< Time lamp off");
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print("\t");
  Serial.println("  Computer time");
  f = mn + 5;
  x ++;                      // Counting on to the next showing day

 m = minuteArray[x];


  Serial.print(x);
  Serial.print("\t");
  Serial.println("  New showing number");
  Serial.print(":");
  Serial.print(m);
  Serial.print("\t");
  Serial.println("  Next showing start (lamp on)");
  Serial.println("------------------------------");
 }

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Jan 27, 2015, 11:38 am
Code: [Select]
o = mn - 4;       //the 8 min delay to heat up the spot
That was not what I was suggesting

What I had in mind was to set up the initial alarmOnce() in setup then, when the alarm triggers do whatever the alarm routine does then, inside the alarm function, set up the next alarmOnce()

This, from the TimeAlarms readme, may be of interest
Quote
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
}
Before you go much further you should be aware that over the period of a year the Arduino oscillator is not very stable so the tigger times will not be accurate.  For accuracy you will need to use an RTC.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Erik_SR on Jan 27, 2015, 02:12 pm
That seems to work. The few seconds time difference wont matter much over the course of a year, but thanks for the tip.

Thank you so much for your help!


Code: [Select]

#include <Time.h>
#include <TimeAlarms.h>

int x;    //Showing Number
int h;    //Spot ON time - hour
int m;    //Spot ON time - minute
int mn;


int o = 1;    //Spot warm up time - minute
int c = 9;    //Shutter close time - minute
int f = 10;    //Spot off time - minute

//Contact Channel set-up
int SpotOn;          //CONTACT 1 -- RED Wire
int ShutterOpen;     //CONTACT 2 -- GREEN Wire
int ShutterClose;    //CONTACT 3 -- BLUE Wire
int SpotOff;         //CONTACT 4 -- YELLOW Wire


int minuteArray[] = {5, 15, 25, 35, 45, 55, 35, 31, 32, 34, 49, 38, 38, 42, 48, 44, 45, 46, 0, 52, 4, 57, 9, 9, 8, 54, 10, 4, 20, 18, 12, 10, 26, 29, 28, 22, 15, 33, 25, 36, 29, 41, 43, 32, 47, 50, 55, 51, 42, 47, 45, 43, 44, 52, 3, 48, 53, 0, 56, 4, 5, 15, 16, 22, 13, 15, 32, 15, 19, 27, 24, 29, 39, 30, 24, 31, 24, 49, 29, 54, 43, 46, 50, 37, 53, 48, 5, 50, 2, 5, 56, 2, 12, 11, 59, 16, 15, 9, 25, 9, 10, 24, 19, 23, 16, 21, 24, 29, 38, 27, 37, 40, 36, 37, 54, 54, 45, 58, 59, 0, 55, 2, 56, 59, 57, 3, 6, 7, 3, 5, 17, 10, 8, 21, 21, 27, 30, 19, 34, 26, 23, 35, 30, 35, 32, 37, 38, 42, 39, 40, 43, 42, 49, 51, 52, 50, 49, 57, 57, 53, 55, 57, 55, 55, 3, 1, 57, 56, 59, 4, 5, 58, 6, 59, 7, 1, 58, 2, 58, 4, 3, 5, 1, 3, 2, 55, 1, 2, 56, 54, 55, 50, 59, 49, 52, 48, 47, 50, 47, 43, 49, 38, 46, 33, 37, 42, 34, 26, 31, 27, 22, 24, 18, 12, 12, 18, 24, 7, 11, 7, 12, 1, 0, 1, 5, 56, 59, 4, 43, 49, 40, 47, 40, 39, 40, 45, 27, 29, 18, 34, 28, 19, 17, 24, 18, 8, 10, 13, 12, 51, 54, 5, 50, 59, 50, 52, 38, 41, 45, 28, 29, 34, 44, 41, 19, 20, 10, 19, 7, 12, 26, 3, 17, 1, 0, 8, 8, 43, 42, 3, 46, 51, 51, 51, 53, 36, 31, 32, 31, 40, 31, 34, 30, 32, 27, 28, 6, 11, 1, 3, 1, 12, 11, 3, 0, 10, 0, 58, 42, 55, 56, 57, 36, 38, 36, 37, 45, 30, 30, 46, 46, 29, 42, 24, 35, 26, 27, 34, 26, 19, 21, 21, 31, 27, 19, 18, 22, 28, 14, 19, 18, 16, 10, 23, 11, 27, 18, 13, 22, 12, 21, 17, 27, 16, 14, 23, 26, 23, 23, 29, 27, 28, 17, 31, 17};


void setup() {
  // initialize serial and wait for port to open:
  Serial.begin(9600);

  //----------------------------------------------------------------------------------------------
  //THESE NEED TO BE ADJUSTED ACCORDIDNG TO CURRENT TIME

  x = 0;                                   // set to showing number

  setTime(17, 17, 0, 2, 1, 15);             // set time to (hours, minutes, seconds, days, months, years)
  //----------------------------------------------------------------------------------------------

  m = minuteArray[x];
  mn = minuteArray[x+1];

  Alarm.alarmOnce(17, 17, o, LampON);        //uncomment for test run with seconds rather than minutes
  Alarm.alarmOnce(17, 17, m, FadeIN);        //set time to 17, 17, 0 and x to 0
  Alarm.alarmOnce(17, 17, c, FadeOUT);
  Alarm.alarmOnce(17, 17, f, LampOFF);

}


void loop() {
 
  m = minuteArray[x];
  mn = minuteArray[x+1];
  Alarm.delay(1000);
 
}


void printDigits(int digits)
{
  Serial.print(":");
  if (digits < 10) {
    Serial.print('0');
  }
  Serial.print(digits);
}



void LampON() {      // This loop is triggered by the alarm
  Serial.println(" ");
  Serial.println("------------------------------");
  Serial.println("Start Showing, lamp preheats");

  Serial.print(x);
  Serial.print("\t");
  Serial.println("  Current Showing number");

  Serial.print(day());
  Serial.print("-");
  Serial.print(month());
  Serial.print("-");
  Serial.print(year());
  Serial.println(" Current Showing date");

  Serial.print(":");
  Serial.print(o);
  Serial.print("\t");
  Serial.println("< Current time: Spot warm-up");

  Serial.print(":");
  Serial.print(m);
  Serial.print("\t");
  Serial.println("  Planned time showing start");

  Serial.print(":");
  Serial.print(c);
  Serial.print("\t");
  Serial.println("  Planned time showing stop");

  Serial.print(":");
  Serial.print(f);
  Serial.print("\t");
  Serial.println("  Planned time spot off");


  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print("\t");
  Serial.println("  Computer time");
  o = mn - 4;       //the 8 min delay to heat up the spot
  Alarm.alarmOnce(17, 17, o, LampON);
 }



void FadeIN() {
  Serial.println("--");
  Serial.println("Lamp fades in");
  Serial.print(":");
  Serial.print(m);
  Serial.print("\t");
  Serial.println("< Time fade-in");
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print("\t");
  Serial.println("  Computer time");
  m = mn;
  Alarm.alarmOnce(17, 17, m, FadeIN);
 }


void FadeOUT() {
  Serial.println("--");
  Serial.println("Lamp fades out");
  Serial.print(":");
  Serial.print(c);
  Serial.print("\t");
  Serial.println("< Time fade-out");
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print("\t");
  Serial.println("  Computer time");
  c = mn + 4;       //the 8 min showing
  Alarm.alarmOnce(17, 17, c, FadeOUT);
}


void LampOFF() {
  Serial.println("--");
  Serial.println("Lamp off, showing ends");
  Serial.print(":");
  Serial.print(f);
  Serial.print("\t");
  Serial.println("< Time lamp off");
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print("\t");
  Serial.println("  Computer time");
  f = mn + 5;
  x ++;                      // Counting on to the next showing day
 
  Serial.print(x);
  Serial.print("\t");
  Serial.println("  New showing number");
  Serial.print(":");
  Serial.print(mn);
  Serial.print("\t");
  Serial.println("  Next showing start (lamp on)");
  Serial.println("------------------------------");
  Alarm.alarmOnce(17, 17, f, LampOFF);
 }
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Jan 27, 2015, 03:04 pm
Quote
The few seconds time difference wont matter much over the course of a year
It is likely to be more than a few seconds.  I have seen estimates that the Arduino will lose or gain up to 1 second per day so over a year that be several minutes and it could be worse.

Something else that I think you should take into account is the need to restart the Arduino during the year.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Erik_SR on Jan 27, 2015, 05:26 pm
Okay. Once every month I will reset the Arduino.

I have noticed that the timer runs every alarm, regardless a desired (1) days wait. Is there a clever way that the Timer library can wait a day before calling the next Alarm.alarmOnce? (I don't mean a full 24 hours waiting. Just calling the next alarm only on the following day.)
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Jan 27, 2015, 05:59 pm
Is the problem that if the time you start the program is say 16:47:22 and you want it to trigger an alarm once at say 17:10:00 tomorrow, it triggers at that time today ?

If so you might want to look at Alarm.timerOnce() which waits not for a specific time but for a specified time period to elapse before triggering.

Or you could set up a single repeating alarm to be triggered a short time after midnight that sets up the alarms for that day.  I suggest doing it just after midnight to prevent any confusion about what day you are setting the alarms for.

Quote
Once every month I will reset the Arduino.
You will need to change the arrays or the array index every time you do this unless you save the current alarm index to EEPROM.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: sfyffe on Jan 27, 2015, 09:23 pm
Hello Everyone,

I have been using the TimeAlarms library to schedule events in my application which is doing very well for me.

How does TimeAlarms work with respect to timerRepeats as far as queuing or sequencing the events?


So for example, I have the following timerRepeats set:


Code: [Select]

Alarm.timerRepeat(30, updateTemperatures);  //defaultsetting.tempFrequency
Alarm.timerRepeat(15, updateCurrent);  //defaultsetting.timeFrequency
Alarm.timerRepeat(600, getSensorConfig);  //defaultsetting.timeFrequency



As these are all individual functions that access Serial1 I am afraid that I can run into contention if timings should cross each other.   Anything in the library that takes care of this?

Best Regards,

Stephen

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Jan 27, 2015, 09:58 pm
When an alarm is created it is given an ID.  The first alarm is ID 0, the second ID 1 etc.  I think that I read somewhere that should 2 or more alarms occur at the same time then they are executed in ID order.  It should be easy enough for you to test.
Title: Time.h not found error ime library don't use
Post by: penguinman76 on Feb 16, 2015, 11:54 pm
Hi,

Arduino environmment 1.6.0

Fatal error Time.h can't be found.

If the Time library is added (Sketch->Import Library->Add library)
The Time Library will be added to the list of installed libraries.

However, it will never work, it will never compile, and it can never be removed.

Solution.

Completely un-install arduino environment.
Re-install arduino environment.
Do not use Time library.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cattledog on Feb 17, 2015, 12:05 am
Quote
Arduino environmment 1.6.0

Fatal error Time.h can't be found.

If the Time library is added (Sketch->Import Library->Add library)
The Time Library will be added to the list of installed libraries.

However, it will never work, it will never compile, and it can never be removed.
That was not my experience. I recently updated from 1.05r2 to 1.6.0 with Windows 7. My first use of the previously installed Time library created a compile error. I removed the old library and installed the latest version from https://github.com/PaulStoffregen/Time (https://github.com/PaulStoffregen/Time) and all works well.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: paprika on Feb 19, 2015, 02:59 am
Not sure if this is the right place, but I'm a bit stuck here.

Is it possible to calculate with alarms or loose bytes with hours, minutes (and seconds)? Example:
//1
byte 1hour    =12;
byte 1minute =59;
byte 1Second =30;
//or Alarm.alarmRepeat(12,59,30, Alarm1);

//2
byte 2hour     =5;
byte 2minute  =0;
byte 2 second =3;
//or Alarm.alarmRepeat(5,0,3, Alarm2);

How to calculate time between 1 and 2 (and then divide that time by X)

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Feb 19, 2015, 08:00 am
Turn both times into seconds since midnight and subtract one time from the other.  If the times span midnight the answer will be negative so add the number of seconds in a day to get the correct result.  Convert back to hours, minutes and seconds using / and % if required.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: paprika on Feb 20, 2015, 04:25 pm
Thnx. :)
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Roy_Krause on Feb 22, 2015, 06:37 pm
I'm a newbie, I admit it! I'm having a problem trying to run TimeSerial on a mega2560. When compiling I get a message that time_t does not name a type. Is there some point I may have overlooked?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Feb 22, 2015, 07:26 pm
Have you #included Time.h ?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Roy_Krause on Feb 22, 2015, 07:55 pm
Yes, Time.h has been included.

I have attached the error output of the compiler:

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.
Arduino: 1.0.6 (Windows 7), Board: "Arduino Mega 2560 or Mega ADK"
TimeSerial:24: error: 'time_t' does not name a type
TimeSerial.pde: In function 'void setup()':
TimeSerial:20: error: 'requestSync' was not declared in this scope
TimeSerial:20: error: 'setSyncProvider' was not declared in this scope
TimeSerial.pde: In function 'void loop()':
TimeSerial:29: error: 'timeStatus' was not declared in this scope
TimeSerial:29: error: 'timeNotSet' was not declared in this scope
TimeSerial:31: error: 'timeSet' was not declared in this scope
TimeSerial.pde: In function 'void digitalClockDisplay()':
TimeSerial:39: error: 'hour' was not declared in this scope
TimeSerial:40: error: 'minute' was not declared in this scope
TimeSerial:41: error: 'second' was not declared in this scope
TimeSerial:43: error: 'day' was not declared in this scope
TimeSerial:45: error: 'month' was not declared in this scope
TimeSerial:47: error: 'year' was not declared in this scope
TimeSerial.pde: In function 'void processSyncMessage()':
TimeSerial:65: error: 'time_t' was not declared in this scope
TimeSerial:65: error: expected `;' before 'pctime'
TimeSerial:69: error: 'pctime' was not declared in this scope
TimeSerial:72: error: 'pctime' was not declared in this scope
TimeSerial:72: error: 'setTime' was not declared in this scope
TimeSerial.pde: At global scope:
TimeSerial:77: error: 'time_t' does not name a type

It seems some file is missing or not the correct version.

 Thanks for your reply.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Feb 22, 2015, 07:57 pm
Now post the program that produced the errors.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Roy_Krause on Feb 22, 2015, 08:04 pm
Here is the program... sorry sketch

/*
 * TimeSerial.pde
 * example code illustrating Time library set through serial port messages.
 *
 * Messages consist of the letter T followed by ten digit time (as seconds since Jan 1 1970)
 * you can send the text on the next line using Serial Monitor to set the clock to noon Jan 1 2010
 T1262347200 
 *
 * A Processing example sketch to automatically send the messages is inclided in the download
 */
 
#include <Time.h> 
tmElements_t tm;
#define TIME_MSG_LEN  11   // time sync to PC is HEADER followed by unix time_t as ten ascii digits
#define TIME_HEADER  'T'   // Header tag for serial time sync message
#define TIME_REQUEST  7    // ASCII bell character requests a time sync message

void setup()  {
  Serial.begin(9600);
  setSyncProvider( requestSync);  //set function to call when sync required
  Serial.println("Waiting for sync message");
}

void loop(){   
  if(Serial.available() )
  {
    processSyncMessage();
  }
  if(timeStatus()!= timeNotSet)   
  {
    digitalWrite(13,timeStatus() == timeSet); // on if synced, off if needs refresh 
    digitalClockDisplay(); 
  }
  delay(1000);
}

void digitalClockDisplay(){
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print(" ");
  Serial.print(day());
  Serial.print(" ");
  Serial.print(month());
  Serial.print(" ");
  Serial.print(year());
  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);
}

void processSyncMessage() {
  // if time sync available from serial port, update time and return true
  while(Serial.available() >=  TIME_MSG_LEN ){  // time message consists of a header and ten ascii digits
    char c = Serial.read() ;
    Serial.print(c); 
    if( c == TIME_HEADER ) {       
      time_t pctime = 0;
      for(int i=0; i < TIME_MSG_LEN -1; i++){   
        c = Serial.read();         
        if( c >= '0' && c <= '9'){   
          pctime = (10 * pctime) + (c - '0') ; // convert digits to a number   
        }
      }   
      setTime(pctime);   // Sync Arduino clock to the time received on the serial port
    } 
  }
}

time_t requestSync()
{
  Serial.print(TIME_REQUEST,BYTE); 
  return 0; // the time will be sent later in response to serial mesg
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cattledog on Feb 22, 2015, 08:42 pm
From the error messages you see, it appears that the Time library is missing, corrupted, or not in the right folder for the IDE to find. It is a user added library. What is the source of your library, and what procedure did you follow to install it?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Roy_Krause on Feb 22, 2015, 09:19 pm
Thanks for the information.


The path to the files is:
Computer>Local Disk(c:)>Users>Roy>My Documents>Arduino>libraries>Time>Time

In that folder I see:


Examples (dir)
Time.h
Time.cpp
Readme
keywords
DateStrings.cpp


http://playground.arduino.cc/uploads/Code/Time.zip
was the source of the files.

Curiously when I first looked in the directory the Time.h file showed as just Time but of a type H,
I did a rename to Time.h which didn't seem to make any difference.





Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cattledog on Feb 22, 2015, 09:31 pm
You have the library in the correct place, but you should not have two folders called Time. The files inside the folder look correct but the path should be
>Arduino>libraries>Time>(then Examples and the .h and .cpp files))
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Roy_Krause on Feb 22, 2015, 09:51 pm
Can I just delete all of the files associated with time and start the installation from scratch? Moving the files didn't seem to help. I did find a file named Time.h.h so I put  that back to being Time.h with no difference.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Feb 22, 2015, 10:07 pm
Code: [Select]
Serial.print(TIME_REQUEST,BYTE);  
This line will cause a problem if you use IDE version 1.0 or later.  The code must be quite old  Change it to
Code: [Select]
Serial.write(TIME_REQUEST);
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Roy_Krause on Feb 22, 2015, 10:26 pm
I am using v1.06 of the IDE. Could you suggest a source for a more recent version of Time?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cattledog on Feb 22, 2015, 10:48 pm
https://github.com/PaulStoffregen/Time

There is a download zip button. It shows up as Time-master. Let the Import Library > Add Library install the zip.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Roy_Krause on Feb 22, 2015, 11:21 pm
I'm not sure how I did it, but somehow I broke the IDE. I get a launch error when I try to start it. I'm going to try removing it and reinstalling it from the git-go..
Thanks for your help.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Roy_Krause on Feb 23, 2015, 12:35 am
Things are going from bad to worse.  Reinstalling the ide didn't work, it went through the install process normally but when I try to run it I get a "Launch4" error message.  Any thoughts on this?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cattledog on Feb 23, 2015, 02:05 am
I don't know what that Launch4 error message is, but if Mr Google and "Arduino Launch4 error message" can't resolve the situation, I would start a new topic in the Installation and Troubleshooting section of the Form with the particulars of your problem.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Roy_Krause on Feb 23, 2015, 12:32 pm
In the wee hours of the morning I found the problem. Somehow I ended up with a nested structure of "libraries" directories in my personal storage locations...I got a libraries directory inside a library directory, etc. The final consequence was that windows couldn't handle the length of the path name, resulting in the "Launch4" error. Mr. Google did point me in the right direction; apparently its not an uncommon situation to get into. The vast amount of time it took to  undo it has made me a more careful person, I even resorted to RTFM about library installation.
I got rid of the pesky directories and re-installed the IDE.
I  installed the time-master library, all went well and it compiled Time-Serial with no error messages. I uploaded it the mega2560 and the serial monitor displayed the waiting for sync message prompt. That's as far as I've gotten but hopefully the rest will be straightforward.
I appreciate all of your help and the very prompt response!
Thanks again,
Roy
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Feb 23, 2015, 12:41 pm
Quote
I even resorted to RTFM about library installation.
Wow - serious stuff.  I am glad you found the problem and cured it.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cattledog on Feb 23, 2015, 04:56 pm
Well done Roy. Do you have any idea of what was causing the nested structure? I believe that when you install a new IDE it preserves the existing Library folder, since its within sketches, so the recursive problem may have come from repeated re-installs of the IDE. In post #375 you had two nested folders. You'll now know what to look for when you finally upgrade to 1.6.0 ;)
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Roy_Krause on Feb 24, 2015, 12:49 am
Thanks cattledog.

That was my assumption, although it certainly doesn't seem that I did that many re-installs. I ended up renaming folders to names like "a1", etc. This pacified windows allowing an rmdir to remove that whole branch of the tree. Its working fine now, in fact I'm quite surprised how accurate the clock is. I  had it running about 6 hours and there was no perceptible error. That might be luck more than anything else.

I did write an excel spreadsheet to calculate the "Tnnnnnnnnnn" string to send to set the clock, if any one wants it.

Thanks again!
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cnwonge on Mar 17, 2015, 05:47 pm
I am newbie in Arduino, would like to have solar battery project to activate one water pump (DO)
Daily For 08:00 am to 11:59 am, the DO has duty cycle of 2 min ON, 8 min OFF.
             12:00 am to 13:59 pm, the DO has duty cycle of 1 min ON, 14 Min OFF.
             14:00 pm to 18:59 pm, the DO has duty cycle of 2 min ON, 13 min OFF.
             19:00 pm to 07:59 am, the DO has duty cycle of 2 min On, 28 min OFF.

If the battery voltage drop to less than 11.44 volt, the DO ON cycle will reduce by 50%.

Thanks
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Mar 17, 2015, 11:20 pm
Please feel free to proceed.

As far as I can see you will require 1 Arduino, 1 Real Time Clock, 1 relay and a suitable power supply.

Do you have any questions ?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cnwonge on Mar 18, 2015, 12:04 am
How about the coding, I  am using RTC1302 actually..
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cnwonge on Mar 18, 2015, 12:04 am
How about the coding, I  am using RTC1302 actually..
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Mar 18, 2015, 08:21 am
Quote
How about the coding
What have you tried ?  What library are you using ?  Does it have any examples ?  Have you tried the TimeAlarms example ?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cnwonge on Mar 22, 2015, 01:58 pm
Here is my coding, the issue is it works, but no refreshing if I plug in the LCD display "Nokia 5110".

 
Code: [Select]

 * TimeAlarmExample.pde
 *Daily For 08:00 am to 11:59 am, the DO has duty cycle of 2 min ON, 8 min OFF.
 *           12:00 am to 13:59 pm, the DO has duty cycle of 1 min ON, 14 Min OFF.
 *            14:00 pm to 18:59 pm, the DO has duty cycle of 2 min ON, 13 min OFF.
 *           19:00 pm to 07:59 am, the DO has duty cycle of 2 min On, 28 min OFF.
 * At startup the time is set to Jan 1 2011  8:29 am
 */

#include <Time.h>
#include <TimeAlarms.h>

void setup()
{
  Serial.begin(9600);
  setTime(11, 59, 45, 1, 1, 11); // set time to Saturday 8:29:00am Jan 1 2011
  // create the alarms
  Alarm.alarmRepeat(8, 00, 0, MorningAlarm); // 8:00am every day
  Alarm.alarmRepeat(12, 00, 0, NoonAlarm); // 12:00am every day
  Alarm.alarmRepeat(14, 00, 0, AfterAlarm); // 14:00pm every day
  Alarm.alarmRepeat(19, 00, 0, EveningAlarm); // 19:00pm every day
   pinMode(13, OUTPUT);
}

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: - Morning off");
  for (int x = 0; x < 24; x++)
 {digitalWrite(13, HIGH);  //打开LED
  delay(120000);                              //延时2 min
  digitalWrite(13, LOW);  //关闭LED
  delay(480000);                             //延时8 min
  Serial.println(x);
}
}
void NoonAlarm() {
  Serial.println("Alarm: - Noon");
  for (int x = 0; x < 8; x++)
  {
    digitalWrite(13, HIGH);  //打开LED
    delay(60000);                          //延时 1 min
    digitalWrite(13, LOW);  //关闭LED
    delay(840000);                         //延时 14 min
    Serial.println(x);
  }

}
void AfterAlarm() {
  Serial.println("Alarm: - Afternoon");
  for (int x = 0; x < 20; x++)
  {
    digitalWrite(13, HIGH);  //打开LED
    delay(120000);                          //延时 2 min
    digitalWrite(13, LOW);  //关闭LED
    delay(780000);                         //延时 13 min
    Serial.println(x);
  }

}
void EveningAlarm() {
  Serial.println("Alarm: - Evening");
  for (int x = 0; x < 22; x++)
  {
    digitalWrite(13, HIGH);  //打开LED
    delay(120000);                          //延时 2 min
    digitalWrite(13, LOW);  //关闭LED
    delay(1680000);                         //延时 28 min
    Serial.println(x);
  }

}

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

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: roontoon on Mar 24, 2015, 03:55 pm
Question... Is it possible to set the arduino internal clock as in setclock(x,x,x,x) from a network time protocol source. if so can you direct me to some sample code that does this. I am trying to adapt the NTP code from Adafruit for the CC3000 which I have working, and the time and timealarms library with which I can't get the alarms to trigger. Thanks so much. Most likely a newbie mistake.

d
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Mar 24, 2015, 06:17 pm
The Arduino does not have an internal clock.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: roontoon on Mar 24, 2015, 07:29 pm
Sorry I meant settime(). It does act like a sudo clock with the settime(x,x,x,x) command, correct? As per http://playground.arduino.cc/Code/Time And if that is in fact true my question is how do you use settime() with NTP? I have tried:

 setTime(timeExtract.hour,timeExtract.min,timeExtract.sec,timeExtract.mon,timeExtract.mday,timeExtract.year);


My main problem with my sketch is that my alarms are not triggering from the TimeAlarms library when trying to set the time with the timeExtract.xxx functions from the NTP code I have working. My current guess as to the problem is that I am not actually setting the time with the above function. If the time is set manually as in  setTime(22,00,0,1,30,15); the alarms work. I don't need a super accurate time for what I am doing and I plan to update the time periodically from the NTP servers. Thanks.

d
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cattledog on Mar 24, 2015, 10:31 pm
Take a look at the example TimeNTP in the Time library. It demonstrates how to sync the internal "clock" to the real world time from an NTP time server.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: pureivory on Apr 02, 2015, 07:02 am
Hey Guys

Just wondering if some one could help me or point me in the right direction, been battling this one for a while and can not seem to win. :(

I currently have the TimeAlarms library turning on and off a pump at specific days and times. So far this has been successful. :) But now I want to extend this by adjusting these times via a touch screen and this is where this issues start happening. I have the screen adjusting variables onAlarmSatHours and onAlarmSatMins etc, but i can't get the alarm to fire at the adjusted time.

Any help would be great.

Thanks

p.s have also attached full sketch

Code: [Select]

#include <Time.h>
#include <TimeAlarms.h>
#include <SimpleTimer.h>
#include <Wire.h>
#include <DS3232RTC.h>
#include <genieArduino.h>
#define I2C_ADDR 0x20 // 0x20 is the address with all jumpers removed
#define RESETLINE 4



//==================Global Variables==================
int onAlarmSatHours = 14;
int onAlarmSatMins = 06;
int offAlarmSatHours = 16;
int offAlarmSatMins = 34;

//====================end=====================


//==================ALARM ID==================
AlarmID_t onAlarmSat, offAlarmSat;
AlarmID_t onAlarmSun, offAlarmSun;

//====================end=====================


void setup()
{
  Serial.begin( 9600 );
  genie.Begin(Serial);

  setSyncProvider(RTC.get); // the function to get the time from the RTC
  // create the alarms

  onAlarmSat = Alarm.alarmRepeat(15, 26, 00, WeeklyAlarmOn);
  offAlarmSat = Alarm.alarmRepeat(15, 26, 30, WeeklyAlarmOff);


}


void loop()
{
  Alarm.delay(0); // calls the alarm functions into action
}


void setNewAlarmTimes() // New alarm settings applied when alarm set button is pressed
{

  Alarm.disable (onAlarmSat);
  Alarm.disable (offAlarmSat);
  Alarm.write(onAlarmSat, AlarmHMS (onAlarmSatHours, onAlarmSatMins, 00));
  Alarm.write(onAlarmSat, AlarmHMS (offAlarmSatHours, offAlarmSatMins, 00));
  Alarm.enable(onAlarmSat);
  Alarm.enable(offAlarmSat);

}


//=========Functions to be called when an alarm triggers =========//

void WeeklyAlarmOn() // Function to turn pool pump on at set time
{
  if bitRead(relayPort, 5) //bitRead gets status of relays
  {
    genie.WriteObject(GENIE_OBJ_4DBUTTON, 0x02, 1); // If relay on, leave on and throw button on
  }
  else
  {
    sendValueToLatch(B100000); // If relay is off, switch relay on  and throw button on
    genie.WriteObject(GENIE_OBJ_4DBUTTON, 0x02, 1);
  }
}

void WeeklyAlarmOff() // Function to turn pool pump off
{
  if bitRead(relayPort, 5) //bitRead gets status of relays
  {
    sendValueToLatch(B100000); // If relay is on, switch relay off and throw button off
    genie.WriteObject(GENIE_OBJ_4DBUTTON, 0x02, 0);
  }
  else
  {
    genie.WriteObject(GENIE_OBJ_4DBUTTON, 0x02, 0); // If relay off, leave off and throw button off
  }
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Apr 02, 2015, 08:27 am
In the program that you posted you are not calling the setNewAlarmTimes() function or have I missed something ?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: pureivory on Apr 02, 2015, 08:56 am
sorry whilst i was removing the unnecessarily code for the touch screen ( to make it easier to read ) i removed it also. I have it being called when the 'set alarm' button is pressed on the screen.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: jc286006 on Apr 08, 2015, 05:32 am
hello all

 i am using time alarms in my aquarium controller sketch.

the daily tasks compile but have not been tested yet.

when i try to set a day of the week task it gives me an error of dowSUNDAY was not declared in this scope.
i am not setting the clock how it is done in the TimeAlarm example because i am using a ds3231 RTC

i have done numerous searches and have not found the fix for the error.

 i have tried a few things that i have found in searches but they have given me even more errors to deal with.

i know its something stupid i am omitting but please enlighten me as to what it is

thanks james
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Apr 08, 2015, 08:37 am
I cannot see anything wrong with the code that you have posted (hint),  but try dowSunday rather than dowSUNDAY ?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: jc286006 on Apr 08, 2015, 05:02 pm
thanks for the reply Helibob

i will try that .  i didnt want to post my whole sketch and it was late when i posted my question so i didnt have  time to post snippets of the offending code if your suggestion doesnt work i will post the code this evening

thanks james
Title: Time synchronous timerRepeat-ed Taskts?
Post by: jim_beam on Apr 09, 2015, 08:18 pm
Hello All,

is it possible to have a "time synchronised" timerRepeat ?

e.g. A task that is repeated every 15min but always at eg.08:00, 8:15, 8:30, 8:45 and so on?

I tried to create a function that starts a timerRepeat at a certain start time to have it synchronous

setSyncTimer( 1.st Start Time <h1.m1.s1>, repeat interval <h2.m2.s2>, CallBack):

Code: [Select]
void setSyncTimer (const int h1, const int m1, const int s1, const int h2, const int m2, const int s2, OnTick_t fcn){
  
   // create the setter
  Alarm.alarmOnce(h1,m1,s1, setter(h2,m2,s2,fcn));
  

void setter(const int h2, const int m2, const int s2, OnTick_t fcn){
     Alarm.alarmRepeat(h2,m2,s2,fcn);  
}


But the Callback function takes no variables.
What would be a solution to it? Creating my own function in the TimeAlarm Class?
Thanks a lot for suggestions.

PS: Actually it would be great if the "setter" fcn is sorting out when would be the next start possibility, e.g. for the above example (ever 15 minutes) if it is 07:33 next would be: 7:45 to start.

Code: [Select]

//something like
next_possible_start_time = last midnight_time;       // 00:00

while( next_possible_start_time  < current time ){   // current time 07:33
next_possible_start_time += Period;                       // period is 00:15
}

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Apr 09, 2015, 10:10 pm
How about setting up an alarm that is triggered at the next due time and runs a function that carries out the required actions for that time then sets up an alarm for 15 minutes in the future that calls the same function, and so on ad infinitum ?  No need to pass parameters to the callback function.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: jim_beam on Apr 10, 2015, 08:13 am
Thank you for the quick reply.

How do I get the time valu of the last midnight time?
Just by substracting the current h.m.s of the total sec since 1970? Or is the a better way?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: TheDarangel on May 14, 2015, 02:12 pm
Hello,

First of all, sorry if my English may be bad ( I'm not English ).

I'm trying to compare the actual time with another variable, for example :

time_t t = now();      <--- this is my actual time variable
time_t hour = 9;        <--- this is the variable I want to compare with.

Here's what I've done :

if(hour(t) == hour(hour)
{
  something();
}

But the condition is always validated, when the numbers are differents too...

Is there another way to do it ?

Thank you for your aswers.


TheDarangel



PS : This is urgent, because it is a school project.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on May 14, 2015, 02:32 pm
Quote
Here's what I've done :

if(hour(t) == hour(hour)
{
  something();
}
Having a variable and a function with the same name is just plain wrong.
Code: [Select]

if(hour(t) == hourToDoSomething)
{
    doSomething();
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: TheDarangel on May 14, 2015, 03:35 pm
Thank you for your answer,

I tryed it, but now, when I put the same hour in the variable, the condition isn't verified.

I don't know what to do :/
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on May 14, 2015, 03:52 pm
Quote
I don't know what to do :/
When in doubt, run in circles, scream, and shout.

When that doesn't work, you could always post your code.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: TheDarangel on May 14, 2015, 05:55 pm
ahah I tryed to run in circles, but the wall was pretty hard xD

My code is really heavy to post it on the forum, here is a pastebin link : [EDIT] didn't posted the good one, here it is : http://pastebin.com/w5WeLC98

Thank you for your help
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on May 14, 2015, 06:24 pm
Quote
My code is really heavy to post it on the forum, here is a pastebin
I can't do pastebin at work, and don't do it at home.

Use the Reply button, not the Quick Reply field. There will be an option at the bottom to attach your code.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: TheDarangel on May 15, 2015, 01:01 pm
Ok, here it is :

Code: [Select]

int Nourr_Moteur = 5;
int Nourr_Recepteur1 = 11;
int Nourr_EtatR1;
int Nourr_Recepteur2 = 12;
int Nourr_EtatR2;
int Nourr_Recepteur3 = 13;
int Nourr_EtatR3;
String Nourr_Restante;

//Camille
int Temp_Lecture = A1;
int Temp_Chauffage = 3;
int Temp_Valeur;

//Nicolas
boolean Ecl_Etat;
int Ecl_Lampe = 10;
float var = 0.04712, out;

//Alexandre
String ip_ordinateur = "192.168.100.69";

boolean reading = false;

time_t EclHd = 11;
String EclHd_String;
time_t EclMd = 5;
String EclMd_String;
time_t EclHf = 11;
String EclHf_String;
time_t EclMf = 6;
String EclMf_String;
int EclV;
String EclV_String;
time_t NourrH = 11;
String NourrH_String;
time_t NourrM = 7;
String NourrM_String;
int TempVj;
String TempVj_String;
int TempVn;
String TempVn_String;
time_t TempHj = 11;
String TempHj_String;
time_t TempHn = 7;
String TempHn_String;

time_t t = now();

byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
IPAddress ip(169,254,112,166);
EthernetServer server(80);

void setup()
{
  Ethernet.begin(mac, ip);   
  server.begin();
  Serial.begin(9600);
 
  //David
  pinMode(Nourr_Recepteur1, INPUT);
  pinMode(Nourr_Recepteur2, INPUT);
  pinMode(Nourr_Recepteur3, INPUT);
 
  //Camille
  pinMode(Temp_Lecture, INPUT);
  pinMode(Temp_Chauffage, OUTPUT);
 
  //Nicolas
  pinMode(Ecl_Lampe, OUTPUT);
}

void loop()

  Serial.println("Boucle loop");
  EthernetClient client = server.available();
  if (client)
  {
    boolean currentLineIsBlank = true;
    String buffer = "";
    while(client.connected())
    {
      if (client.available())
      {
        char c = client.read();
        Serial.print(c);
        buffer+=c;
       
        if (c == '\n' && currentLineIsBlank)
        {
          NourritureRestante();
          TemperatureLecture();
         
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();
         
         
         
          client.print("Temp=");
          client.print(Temp_Valeur);
          client.print("Ecl=");
          client.print(Ecl_Etat);
          client.print("Nourr=");
          client.print(Nourr_Restante);
         
          client.print("<br></br>");
          client.print("EclHd=");
          client.print(EclHd);
          client.print("<br/>");
          client.print("EclMd=");
          client.print(EclMd);
          client.print("<br/>");
          client.print("EclHf=");
          client.print(EclHf);
          client.print("<br/>");
          client.print("EclMf=");
          client.print(EclMf);
          client.print("<br/>");
          client.print("EclV=");
          client.print(EclV);
          client.print("<br/>");
          client.print("NourrH=");
          client.print(NourrH);
          client.print("<br/>");
          client.print("NourrM=");
          client.print(NourrM);
          client.print("<br/>");
          client.print("TempVj=");
          client.print(TempVj);
          client.print("<br/>");
          client.print("TempVn=");
          client.print(TempVn);
          client.print("<br/>");
          client.print("TempHj=");
          client.print(TempHj);
          client.print("<br/>");
          client.print("TempHn=");
          client.print(TempHn);
          client.print("<meta http-equiv='refresh' content='0.1; URL=");
          client.print(ip_ordinateur);
          client.print("'>");
         
          break;
        }
        if (c == '\n')
        {
          currentLineIsBlank = true;
          buffer = "";
        }
        else if (c != '\r')
        {
          if(buffer.indexOf("P=") > 0)
          {
            int readPosition = buffer.indexOf("P=");
           
            EclHd_String = buffer.substring(readPosition+2, readPosition+4);
            EclMd_String = buffer.substring(readPosition+4, readPosition+6);
            EclHf_String = buffer.substring(readPosition+6, readPosition+8);
            EclMf_String = buffer.substring(readPosition+8, readPosition+10);
           
            EclV_String = buffer.substring(readPosition+10, readPosition+12);
           
            NourrH_String = buffer.substring(readPosition+12, readPosition+14);
            NourrM_String = buffer.substring(readPosition+14, readPosition+16);
           
            TempVj_String = buffer.substring(readPosition+16, readPosition+18);
            TempVn_String = buffer.substring(readPosition+18, readPosition+20);
            TempHj_String = buffer.substring(readPosition+20, readPosition+22);
            TempHn_String = buffer.substring(readPosition+22, readPosition+24);
           
            EclHd = EclHd_String.toInt();
            EclMd = EclMd_String.toInt();
            EclHf = EclHf_String.toInt();
            EclMf = EclMf_String.toInt();
           
            EclV = EclV_String.toInt();
           
            NourrH = NourrH_String.toInt();
            NourrM = NourrM_String.toInt();
           
            TempVj = TempVj_String.toInt();
            TempVn = TempVn_String.toInt();
            TempHj = TempHj_String.toInt();
            TempHn = TempHn_String.toInt();
           
          }
          else
          {
            currentLineIsBlank = false;
          }
        }
      }
    }
    delay(1);
    client.stop();
  }
 
  if(hour(t) == EclHd && minute(t) == EclMd)
  {
    EclairageDebut();
  }
 
  if(hour(t) == EclHf && minute(t) == EclMf)
  {
    EclairageFin();
  }
 
  if(hour(t) == TempHj)
  {
    TemperatureJour();
  }
 
  if(hour(t) == TempHn)
  {
    TemperatureNuit();
  }
 
}



void EclairageDebut()
{
  Serial.println("Alarme Eclairage Début");
  Ecl_Etat = 1;
 
  if(hour(t) < hour(EclHf) && minute(t) < minute(EclMf))
  {
    digitalWrite(Ecl_Lampe, HIGH);
    Serial.println("Lampe Allumée");
    for(var; var < 0.10995; var = var + 0.1) // var incrémente de 0.1 a chaque fois jusqu'a atteindre 0.10995 en commencant à 0.04712
    {
      out = sin(var) * 127.5 + EclV; //127.5 = 255/2 soit 50% de la luminosité
      analogWrite(Ecl_Lampe, out);
    }
  }
 
  else
  {
   digitalWrite(Ecl_Lampe, LOW);
   Serial.println("Lampe Eteinte");
  }
}

void EclairageFin()
{
  Serial.println("Alarme Eclairage Fin");
  Ecl_Etat = 0;
}

void DistributionNourriture()
{
  Serial.println("Alarme Distribution Nourriture");
 
  for(compteur; compteur < temps_moteur; compteur++)
  {
  digitalWrite(Nourr_Moteur, HIGH);
  Serial.println("Moteur allumé");
  }
 
  digitalWrite(Nourr_Moteur, LOW);
  Serial.println("Moteur étteint");
 
}


void NourritureRestante()
{
  Serial.println("Alarme Nourriture Restante");
  Nourr_EtatR1 = digitalRead(Nourr_Recepteur1);
  Nourr_EtatR2 = digitalRead(Nourr_Recepteur2);
  Nourr_EtatR3 = digitalRead(Nourr_Recepteur3);
 
  if(Nourr_EtatR1 == LOW && Nourr_EtatR2 == LOW && Nourr_EtatR3 == LOW)
  {
    Nourr_Restante = "4/4";
  }
 
  if(Nourr_EtatR1 == HIGH)
  {
    Nourr_Restante = "3/4";
  }
 
  if(Nourr_EtatR2 == HIGH)
  {
    Nourr_Restante = "2/4";
  }
 
  if(Nourr_EtatR3 == HIGH)
  {
    Nourr_Restante = "1/4";
  }
}


void TemperatureLecture()
{
  Temp_Valeur = digitalRead(Temp_Lecture);
}


void TemperatureJour()
{
  Serial.println("Alarme Temperature Jour");
}

void TemperatureNuit()
{
  Serial.println("Alarme Temperature Jour");
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on May 15, 2015, 04:33 pm
Code: [Select]
time_t EclHd = 11;
That is not proper data to initialize a time_t type variable. The type you want is uint8_t.

Code: [Select]
  if(hour(t) == EclHd && minute(t) == EclMd)
  {
    EclairageDebut();
  }

t is the time the Arduino restarted. Is that reasonable? You are comparing apples and oranges here. The hour() extracts the hour portion of the time_t structure. You are comparing that to a time_t (which is the wrong type) structure.

You need to set a flag when you do call EclairageDebut(), so that you don't call it thousands of times while the hour and minute values match. You need to call the function only when the flag is clear. You need to clear the flag when the hour and minute values don't match.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: TheDarangel on May 18, 2015, 09:14 am
Hello,

Sorry for the time I took to reply, I'll try it this afternoon, thank you for your help :)
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: TheDarangel on May 18, 2015, 04:19 pm
I'm back,

It didn't worked :/ may be I've made something wrong...

Here's the new code :

Code: [Select]
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
#include <Time.h>
#include <TimeAlarms.h>

//David
int temps_moteur = 3; //temps de fonctionnement du moteur ( en secondes );
int compteur;

int Nourr_Moteur = 5;
int Nourr_Recepteur1 = 11;
int Nourr_EtatR1;
int Nourr_Recepteur2 = 12;
int Nourr_EtatR2;
int Nourr_Recepteur3 = 13;
int Nourr_EtatR3;
String Nourr_Restante;

//Camille
int Temp_Lecture = A1;
int Temp_Chauffage = 3;
int Temp_Valeur;

//Nicolas
boolean Ecl_Etat;
int Ecl_Lampe = 10;
float var = 0.04712, out;

//Alexandre
String ip_ordinateur = "192.168.100.69";

boolean reading = false;

uint8_t EclHd = 16;
String EclHd_String;
uint8_t EclMd = 16;
String EclMd_String;
uint8_t EclHf = 16;
String EclHf_String;
uint8_t EclMf = 18;
String EclMf_String;
int EclV;
String EclV_String;

boolean Ecld_Once = false;
boolean Eclf_Once = false;

uint8_t NourrH = 16;
uint8_t NourrH_After = NourrH+1;
String NourrH_String;
uint8_t NourrM = 15;
String NourrM_String;

boolean Nourr_Once = false;

int TempVj;
String TempVj_String;
int TempVn;
String TempVn_String;
uint8_t TempHj = 16;
String TempHj_String;
uint8_t TempHn = 17;
String TempHn_String;

boolean TempJ_Once = false;
boolean TempN_Once = false;

time_t t = now();

byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
IPAddress ip(169,254,20,152);
EthernetServer server(80);

void setup()
{
  Ethernet.begin(mac, ip);   
  server.begin();
  Serial.begin(9600);
 
  //David
  pinMode(Nourr_Recepteur1, INPUT);
  pinMode(Nourr_Recepteur2, INPUT);
  pinMode(Nourr_Recepteur3, INPUT);
 
  //Camille
  pinMode(Temp_Lecture, INPUT);
  pinMode(Temp_Chauffage, OUTPUT);
 
  //Nicolas
  pinMode(Ecl_Lampe, OUTPUT);
}

void loop()

  Serial.println("Boucle loop");
  EthernetClient client = server.available();
  if (client)
  {
    boolean currentLineIsBlank = true;
    String buffer = "";
    while(client.connected())
    {
      if (client.available())
      {
        char c = client.read();
        Serial.print(c);
        buffer+=c;
       
        if (c == '\n' && currentLineIsBlank)
        {
          NourritureRestante();
          TemperatureLecture();
         
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();
         
         
         
          client.print("Temp=");
          client.print(Temp_Valeur);
          client.print("Ecl=");
          client.print(Ecl_Etat);
          client.print("Nourr=");
          client.print(Nourr_Restante);
         
          client.print("<br></br>");
          client.print("EclHd=");
          client.print(EclHd);
          client.print("<br/>");
          client.print("EclMd=");
          client.print(EclMd);
          client.print("<br/>");
          client.print("EclHf=");
          client.print(EclHf);
          client.print("<br/>");
          client.print("EclMf=");
          client.print(EclMf);
          client.print("<br/>");
          client.print("EclV=");
          client.print(EclV);
          client.print("<br/>");
          client.print("NourrH=");
          client.print(NourrH);
          client.print("<br/>");
          client.print("NourrM=");
          client.print(NourrM);
          client.print("<br/>");
          client.print("TempVj=");
          client.print(TempVj);
          client.print("<br/>");
          client.print("TempVn=");
          client.print(TempVn);
          client.print("<br/>");
          client.print("TempHj=");
          client.print(TempHj);
          client.print("<br/>");
          client.print("TempHn=");
          client.print(TempHn);
          client.print("<meta http-equiv='refresh' content='0.1; URL=");
          client.print(ip_ordinateur);
          client.print("'>");
         
          break;
        }
        if (c == '\n')
        {
          currentLineIsBlank = true;
          buffer = "";
        }
        else if (c != '\r')
        {
          if(buffer.indexOf("P=") > 0)
          {
            int readPosition = buffer.indexOf("P=");
           
            EclHd_String = buffer.substring(readPosition+2, readPosition+4);
            EclMd_String = buffer.substring(readPosition+4, readPosition+6);
            EclHf_String = buffer.substring(readPosition+6, readPosition+8);
            EclMf_String = buffer.substring(readPosition+8, readPosition+10);
           
            EclV_String = buffer.substring(readPosition+10, readPosition+12);
           
            NourrH_String = buffer.substring(readPosition+12, readPosition+14);
            NourrM_String = buffer.substring(readPosition+14, readPosition+16);
           
            TempVj_String = buffer.substring(readPosition+16, readPosition+18);
            TempVn_String = buffer.substring(readPosition+18, readPosition+20);
            TempHj_String = buffer.substring(readPosition+20, readPosition+22);
            TempHn_String = buffer.substring(readPosition+22, readPosition+24);
           
            EclHd = EclHd_String.toInt();
            EclMd = EclMd_String.toInt();
            EclHf = EclHf_String.toInt();
            EclMf = EclMf_String.toInt();
           
            EclV = EclV_String.toInt();
           
            NourrH = NourrH_String.toInt();
            NourrM = NourrM_String.toInt();
           
            TempVj = TempVj_String.toInt();
            TempVn = TempVn_String.toInt();
            TempHj = TempHj_String.toInt();
            TempHn = TempHn_String.toInt();
           
          }
          else
          {
            currentLineIsBlank = false;
          }
        }
      }
    }
    delay(1);
    client.stop();
  }
 
  if(hour(t) == EclHd && minute(t) == EclMd && Ecld_Once == false)
  {
    Ecld_Once = true;
    Eclf_Once = false;
    EclairageDebut();
  }
 
  if(hour(t) == EclHf && minute(t) == EclMf && Eclf_Once == false)
  {
    Eclf_Once = true;
    Ecld_Once = false;
    EclairageFin();
  }
 
  if(hour(t) == TempHj && TempJ_Once == false)
  {
    TempJ_Once = true;
    TempN_Once = false;
    TemperatureJour();
  }
 
  if(hour(t) == TempHn && TempN_Once == false)
  {
    TempN_Once = true;
    TempJ_Once = false;
    TemperatureNuit();
  }
 
  if(hour(t) == NourrH && minute(t) == NourrM && Nourr_Once == false)
  {
    Nourr_Once = true;
    DistributionNourriture();
  }
 
  if(hour(t) == NourrH_After)
  {
    Nourr_Once = false;
  }
}



void EclairageDebut()
{
  Serial.println("Alarme Eclairage Début");
  Ecl_Etat = 1;
 
  if(hour(t) < hour(EclHf) && minute(t) < minute(EclMf))
  {
    digitalWrite(Ecl_Lampe, HIGH);
    Serial.println("Lampe Allumée");
    for(var; var < 0.10995; var = var + 0.1) // var incrémente de 0.1 a chaque fois jusqu'a atteindre 0.10995 en commencant à 0.04712
    {
      out = sin(var) * 127.5 + EclV; //127.5 = 255/2 soit 50% de la luminosité
      analogWrite(Ecl_Lampe, out);
    }
  }
 
  else
  {
   digitalWrite(Ecl_Lampe, LOW);
   Serial.println("Lampe Eteinte");
  }
}

void EclairageFin()
{
  Serial.println("Alarme Eclairage Fin");
  Ecl_Etat = 0;
}

void DistributionNourriture()
{
  Serial.println("Alarme Distribution Nourriture");
 
  for(compteur; compteur < temps_moteur; compteur++)
  {
  digitalWrite(Nourr_Moteur, HIGH);
  Serial.println("Moteur allumé");
  }
 
  digitalWrite(Nourr_Moteur, LOW);
  Serial.println("Moteur étteint");
 
}


void NourritureRestante()
{
  Serial.println("Alarme Nourriture Restante");
  Nourr_EtatR1 = digitalRead(Nourr_Recepteur1);
  Nourr_EtatR2 = digitalRead(Nourr_Recepteur2);
  Nourr_EtatR3 = digitalRead(Nourr_Recepteur3);
 
  if(Nourr_EtatR1 == LOW && Nourr_EtatR2 == LOW && Nourr_EtatR3 == LOW)
  {
    Nourr_Restante = "4/4";
  }
 
  if(Nourr_EtatR1 == HIGH)
  {
    Nourr_Restante = "3/4";
  }
 
  if(Nourr_EtatR2 == HIGH)
  {
    Nourr_Restante = "2/4";
  }
 
  if(Nourr_EtatR3 == HIGH)
  {
    Nourr_Restante = "1/4";
  }
}


void TemperatureLecture()
{
  Temp_Valeur = digitalRead(Temp_Lecture);
}


void TemperatureJour()
{
  Serial.println("Alarme Temperature Jour");
}

void TemperatureNuit()
{
  Serial.println("Alarme Temperature Jour");
}
 
         


Thanks a lot for your help
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on May 18, 2015, 05:12 pm
Quote
It didn't worked :/ may be I've made something wrong...
It did something. I can't see your serial output. I have no idea what time it was when you tried. I have no idea what time you told it to do whatever.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: TheDarangel on May 18, 2015, 05:17 pm
I tried it for EclHd = 16; EclMd = 16 ( 16:16 pm) but it always printed me Boucle loop, nothing else

to be sure, I sent the program while it was 16:14 pm and I waited the Serial to print me something else than Boucle loop but... nothing apeared
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on May 18, 2015, 05:40 pm
Quote
to be sure, I sent the program while it was 16:14 pm and I waited the Serial to print me something else than Boucle loop but... nothing apeared
Then, no client connected to your server, and none of your code ever ran.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: TheDarangel on May 19, 2015, 11:13 am
yes, the server is only to send the new settings, but I don't know why the conditions can't be verified :/

If it is possible, I want the program to be able ton run when no one connect the server
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: tobasco on Jun 11, 2015, 09:31 pm
Hi,
when I tried to present the supported date range in the GUI I found a bug in the Time library:

static tmElements_t tm;
static time_t cacheTime;
void refreshCache(time_t t) {
  if (t != cacheTime) {
    breakTime(t, tm);
    cacheTime = t;
  }
}

If during the FIRST call the argument t is 0 then the uninitialized cache will not be refreshed and relaying functions like day(t), month(t) and weekday(t) return wrong values (Err 00/00/1970).
It can be easily fixed by initialize the cache properly:

static tmElements_t tm = {0, 0, 0, 5, 1, 1, 0};


salute & thanks for this great lib
Thomas
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Jun 15, 2015, 08:39 pm
Quote
It can be easily fixed by initialize the cache properly:
How do you expect the library to deal with garbage? Why are you supplying it garbage? Why do you think the library should deal with garbage differently?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: lympe_k on Jun 28, 2015, 12:07 pm
Hi,

I have a question for you guys.

In the Time Alarm Example i change the

Code: [Select]
setTime(8,29,0,1,1,11);

with the

Code: [Select]
setSyncProvider(RTC.get);


And I think this will take the time from my RTC and trigger my allarms. But NOT.

To make it work i must open the Serial Port from my IDE, only then trigger the allarms.

And what I want is to not be involved the Serial Port to trigger my alarms.


Sorry for my English.

Thanks !
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cattledog on Jun 28, 2015, 05:25 pm
 How do you know the alarms don't work without the monitor open? In the example sketch as written, the only way to see the alarms being activated is with the printouts on the serial monitor.

Declare pin 13 as an output and add the following to the 15 second repeat alarm. The on board led goes on and off every 15 seconds without the serial monitor open.
Code: [Select]
void Repeats(){
  Serial.println("15 second timer");
  digitalWrite(13,!digitalRead(13));
}

If this does not work this way for you, you will have to post the code which demonstrates your problem. Be sure to use the code tags <\> from the tool bar when you do so and post your code between the two words "code" in brackets.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: lympe_k on Jun 28, 2015, 07:50 pm
Thanks for the reply cattledog.

I've tried with a LED of course. And i know that my RTC it has the correct time(i don't know for the sync). I have manage the alarms to trigger but only when i have opened the serial port first.

Code: [Select]
#include <Wire.h>
#include <DS3232RTC.h>
#include <Time.h>
#include <TimeAlarms.h>

int LedPin = 12 ;

void setup()
{
  pinMode(LedPin, OUTPUT);
  setSyncProvider(RTC.get);
 
  Alarm.alarmRepeat(20,30,0, AlarmOn); 
  Alarm.alarmRepeat(20,31,0, AlarmOff);   
 
}

void  loop(){ 
  //Nothing in the loop for this example
}

void AlarmOn(){
  Serial.println("Alarm: - Turn Led ON");
  digitalWrite(LedPin, HIGH); 
}

void AlarmOff(){
  Serial.println("Alarm: - Turn Led OFF");
  digitalWrite(LedPin, LOW);
}


I have noticed without the following code the alarms dont work, but when i put this code to above example, alarms are triggered.

Code: [Select]
void  loop(){ 
  digitalClockDisplay();
  Alarm.delay(1000);
}

void digitalClockDisplay()
{
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.println();
}

void printDigits(int digits)
{
  Serial.print(":");
  if(digits < 10)
  Serial.print('0');
  Serial.print(digits);
}



Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Jun 28, 2015, 08:16 pm
There is no Alarm.delay() in your first code example so the alarms will not be checked and triggered.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: lympe_k on Jun 28, 2015, 09:12 pm
That seems to be the solution. Thanks very much for the help!

Something else, can i change the set time of my alarms when the program runs? And how that is possible?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Jun 28, 2015, 11:09 pm
Quote
can i change the set time of my alarms when the program runs? And how that is possible?
If you replace the fixed values in the alarm setting functions with variables then you could write code to allow the user to change the values and hence change the alarm times.  Is that what you meant ?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: lympe_k on Jun 28, 2015, 11:16 pm
Εxactly!
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: MitchSF on Jun 29, 2015, 02:14 am
Hi All,

I have a nixie project that's using the Time library and syncing with an RTC set up as the sync provider. That works perfectly. What I'm trying to do is to occasionally sync with GPS, using TinyGPSPlus. Data coming from the GPS is perfect and it passes isValid() checks. setTime() does not work. The issue is probably my understanding of how the time library works. Help is appreciated.



Code: [Select]
void syncGPS() {


 
  if (gps.date.isValid() && gps.time.isValid() && gps.time.age() < 2000) {
   tmElements_t tm;
   tm.Hour = gps.time.hour();
   tm.Minute = gps.time.minute();
   tm.Second = gps.time.second();
   tm.Year = gps.date.year();
   tm.Month = gps.date.month();
   tm.Day = gps.date.day();

   time_t time = makeTime(tm);
   setTime(time);
   adjustTime(gpsOffset);
 
//   RTC.set(time);
  }
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cattledog on Jun 29, 2015, 05:24 am
I do not think that you are handling tm.year correctly. As a raw value, tm.year is the number of years since 1970, i.e. 45 for 2015. The gps.date.year() is returning a year value that is likely either four digits 2015 or  possibly two digits 15.

There are two time library functions to adjust the calendar year (two or four digits) to tm.year. CalendarYrToTm() and y2kYearToTm().  Here is a snippet showing how the calendar year can be handled.

Code: [Select]


int y = gps.date.year();

if (y >= 1000)
  tm.Year = CalendarYrToTm(y);
  else    //(y < 100)
  tm.Year = y2kYearToTm(y);


Alternatively you can just do the subtraction/addition

Code: [Select]
tm.year = gps.date.year() -1970; //for four digit year
tim.year = gps.date.year() + 30;//for two digit year



Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: lympe_k on Jun 29, 2015, 11:27 am
UKHeliBob

"If you replace the fixed values in the alarm setting functions with variables then you could write code to allow the user to change the values and hence change the alarm times"

Can you give me a code example for what I asked? Or some links referred to this?

Thank you very much for your help!
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Jun 29, 2015, 01:07 pm
If you look at this thread Serial input basics (http://forum.arduino.cc/index.php?topic=288234.0) you will find examples of getting user input.  Once you have the user input you can use the value(s) in the alarm setting functions.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: MitchSF on Jun 30, 2015, 01:35 pm
I do not think that you are handling tm.year correctly.
Thank you. I added the subtraction and tm.Year is now correct. But still I don't seem to have a handle on how this works. For example:

Code: [Select]

(continued)
 tm.Month = gps.date.month();
    tm.Day = gps.date.day();
 
 //   t = makeTime(tm);

 
    setTime(tm.Hour, tm.Minute, tm.Second, tm.Day, tm.Month, tm.Year);
now();
    //   setTime(t);


This works without, but substituting makeTime(tm) and setTime(t);, does not work. I think it should because t should have GPS time. Subtracting the offset from t in seconds, then adding:

breakTime(t, tm);, to update the "tm" variable, does not work. Is there a lapse in logic here? adjustTime(offset) does not work, either. I tried adding now() in various places, to no effect.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cattledog on Jun 30, 2015, 08:49 pm
Quote
This works without, but substituting makeTime(tm) and setTime(t);, does not work. I think it should because t should have GPS time. Subtracting the offset from t in seconds, then adding:

breakTime(t, tm);, to update the "tm" variable, does not work. Is there a lapse in logic here? adjustTime(offset) does not work, either. I tried adding now() in various places, to no effect.
Here is a small demonstration of some of the time library functions which seem to be giving you problems.
Code: [Select]
#include <Time.h>

tmElements_t tm;
time_t t;

void setup() {

  Serial.begin(9600);

  //your gps values will go here
  //they do not have to be tm elements for setTime()
  int Year = 2015;
  byte Month = 6;
  byte Day = 30;
  byte Hour = 11;
  byte Minute = 12;
  byte Second = 13;
  unsigned long gpsOffset = 3600;

  Serial.println("setTime with time/date values");
  setTime(Hour, Minute, Second, Day, Month, Year); //setting AVR time
  display_Time();

  Serial.println("setTime with unixTime time_t value");
  t = now();
  setTime(t);
  display_Time();

  Serial.println("setTime with makeTime(tm)");
  breakTime(t, tm);
  setTime(makeTime(tm));
  display_Time();

  Serial.println("adjustTime plus one hour");
  adjustTime(gpsOffset);
  display_Time();

}

void loop() {

  display_Time();
  delay(5000);
}

void display_Time(void)
{
  Serial.print("Time.h library configured Time = ");
  Serial.print(hour());
  Serial.write(':');
  print2digits(minute());
  Serial.write(':');
  print2digits(second());
  Serial.print(", Date (D/M/Y) = ");
  Serial.print(day());
  Serial.print('/');
  Serial.print(month());
  Serial.print('/');
  Serial.print(year());
  Serial.println();
  Serial.print("Unix Time ");
  t = now();
  Serial.println(t);
  Serial.println();
}

void print2digits(int number) {
  if (number >= 0 && number < 10) {
    Serial.write('0');
  }
  Serial.print(number);
}

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: MitchSF on Jul 01, 2015, 12:07 am
Well...you were right. The bad date value was the issue. Thanks again!
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: namen on Jul 19, 2015, 05:50 pm
Hi,

I have a question for you.
I am working on a watering system. But I cant figure out TimeAlarm library. It should be simple but for some reason it just doesnt work.

I have basically two repeating timers. Those should do morning and evening watering. I want to have the ability to change time of the watering. So I need to change the trigger time for both of those timers. But it just fires the trigger for a first time, not after the change of trigger time.

My code is quite big to post but even when I slightly modify the shipping TimeAlarm example with same functions it doesnt do what I expect it to do.

I expect firing triggers at
8:30:00
8:30:05
8:30:10
8:30:15
But it just do the first two, than nothing..

What am I missing?


Code: [Select]
#include <Time.h>
#include <TimeAlarms.h>

 AlarmID_t Timer1st_id = 0;  // this will be the ID for the first allocated alarm
 AlarmID_t Timer2nd_id = 1; // ID for the seconds alarm

void setup()
{
  Serial.begin(9600);
  setTime(8,29,55,1,1,11); // set time to Saturday 8:29:00am Jan 1 2011
  // create the alarms
  Timer1st_id = Alarm.alarmRepeat(8,30,0, MorningAlarm);  // 8:30am every day
  Timer2nd_id = Alarm.alarmRepeat(8,30,5, EveningAlarm);  // 5:45pm every day
}

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");
  Alarm.write(Timer1st_id , AlarmHMS(8, 30, 10));
  Alarm.enable(Timer1st_id);
}

void EveningAlarm(){
  Serial.println("Alarm: - turn lights on"); 
  Alarm.write(Timer2nd_id , AlarmHMS(8, 30, 15));
  Alarm.enable(Timer2nd_id); 
}

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);
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: namen on Jul 19, 2015, 06:58 pm
And weird thing is if I turn it the other way around and set the system time after firing the second trigger backwards a few seconds I would expect to those triggers to be fired again if they are set to Repeat every day at 8:30:00 and at 8:30:05. But nothing happen. Both triggers fire only once.

please help. Im stuck with this for some time.

Code: [Select]
#include <Time.h>
#include <TimeAlarms.h>

 AlarmID_t Timer1st_id = 0;  // this will be the ID for the first allocated alarm
 AlarmID_t Timer2nd_id = 1; // ID for the seconds alarm

void setup()
{
  Serial.begin(9600);
  setTime(8,29,55,1,1,11); // set time to Saturday 8:29:00am Jan 1 2011
  // create the alarms
  Timer1st_id = Alarm.alarmRepeat(8,30,0, MorningAlarm);  // 8:30am every day
  Timer2nd_id = Alarm.alarmRepeat(8,30,5, EveningAlarm);  // 5:45pm every day
}

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"); 
  setTime(8,29,55,1,1,11); // set time to Saturday 8:29:00am Jan 1 2011 
}

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);
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Clemens on Aug 28, 2015, 03:28 pm
I'm searching still for an approach to combine TimeAlarms and a power saving lib. Is there any code to use instead the Alarm.delay function a modified version that sends the MC to sleep and waking it up at the next alarm item?

I posted a time ago some ideas:
http://forum.arduino.cc/index.php?topic=291983.0
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Aug 28, 2015, 03:49 pm
Quote
Is there any code to use instead the Alarm.delay function a modified version that sends the MC to sleep and waking it up at the next alarm item?
You would need to modify the Alarm.delay() static method. Does the clock keep ticking in your sleep mode? If not, then it is silly to talk about sleeping for n ticks.

An RTC that can generate an external interrupt is going to far simpler to incorporate into you project, I suspect.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: jim_beam on Aug 28, 2015, 04:42 pm
I'm searching still for an approach to combine TimeAlarms and a power saving lib. Is there any code to use instead the Alarm.delay function a modified version that sends the MC to sleep and waking it up at the next alarm item?

I posted a time ago some ideas:
http://forum.arduino.cc/index.php?topic=291983.0
Hello Clemens,

I was looking for the same but could not find a solution, so I stared my own Task-Scheduler Library that puts the Controller to low Power Sleep Mode when all Tasks are done till the next Task needs to be executed.

In that mode the Timers are stopped, but since I periodically wake the Controller with the WDT ever 16ms to 8 Sec and add the recent sleeped_ms to a total_sleeped_ms variable I still know the time. I wrote my own millis()-Function called mils() returning millis() + total_sleeped_ms.

I also included an RTC and synchronised the milliseconds periodically.

It does work well. But since I am not a professional Programmer it does take quite a long time to have it in a nice library (so far I was testing it as long single file code).

I cant give you a working solution now, but some more hints and -not-yet-finished-code if you are interested.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Clemens on Aug 28, 2015, 09:13 pm
Yes, Paul, the hardware version with RTC and interrupt is a good solution for recurring events, say "do the same every 5 minutes".

The nice thing on TimeAlarms is that you can combine "alarms" and "timer": Measure every 5 minutes, do an upload once a day at 7pm, delete SD backup every Saturday evening.

Is there a RTC lib similar to TimeAlarms where I can combine this different "alarms" and "timer" and use RTC plus interrupt to trigger the wakeup?

I tried also to mix Narcoleptic and TimeAlarms: After a task is done, I had a look for the next TimeAlarms event and sent the arduino via Narcoleptic to sleep, exactly the time from now to the next event. Narcoleptic recalculates the time to get more accurate time information and so the "real time" drifts more and more ... it's complicated I think it leads to more problems in case you synchronize time with an external server.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cattledog on Aug 28, 2015, 09:39 pm
The DS3231(or DS3232) is an accurate RTC with two alarms which can be configured to trigger an interrupt. You can use it with or without the Time or Time Alarms library. In my opinion, the best library to use if you don't want to write the i2c commands yourself is Jack Christensen's https://github.com/JChristensen/DS3232RTC (https://github.com/JChristensen/DS3232RTC)
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Aug 28, 2015, 11:13 pm
Quote
Is there a RTC lib similar to TimeAlarms where I can combine this different "alarms" and "timer" and use RTC plus interrupt to trigger the wakeup?
How would YOU perform tasks at assigned times, given just a watch with date display? It isn't rocket science to determine that today is August 28, 2015, and that I have a doctors appointment at 9:30, so I should be at the doctor's office at 9:30.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Clemens on Aug 29, 2015, 12:00 am
The problem afaik is the combination of a sleep mode and the TimeAlarm lib. A deep sleep mode disables the "ticking" as Paul mentioned, that is needed for the lib's internal time counting. I wonder if it is working to update time via RTC direct after waking up:

- waiting to the end of the current task
- find out the next event scheduled by TimeAlarm
- set the date/time for this event as an alarm on the RTC
- send MC to sleep
- ... waiting ...
- IRQ wakes MC up
- sync the lib's time with calling now(); or call getTimeFunction()
- hopefully the via TimeAlarm specified function will run


hmmmm, could work in case the internal representative for the time is also updated but in the readme it sounds not so

Quote
Q: How are scheduled tasks affected if the system time is changed?
A: Tasks are scheduled for specific times designated by the system clock.
If the system time is reset to a later time (for example one hour ahead) then all
alarms and timers will occur one hour later.
If the system time is set backwards (for example one hour back) then the alarms and timers will occur an hour earlier.
If the time is reset before the time a task was scheduled, then the task will be triggered on the next service (the next call to Alarm.delay).
This is  the expected behaviour for Alarms � tasks scheduled for a specific time of day will trigger at that time, but the affect on timers may not be intuitive. If a timer is scheduled to trigger in 5 minutes time and the clock is set ahead by one hour, that timer will not trigger until one hour and 5 minutes has elapsed.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Clemens on Aug 29, 2015, 12:04 am
In case I have only one appointment at 9:30 it is easy, but in case I have an recurring event every 15 minutes, a second one every hour, some daily and one weekly its getting complicate. So the TimeAlarms lib is nice and I like to combine it with RTC and interrupt driven. But perhaps I think too complicated ...
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Aug 29, 2015, 12:36 am
Quote
In case I have only one appointment at 9:30 it is easy, but in case I have an recurring event every 15 minutes, a second one every hour, some daily and one weekly its getting complicate. So the TimeAlarms lib is nice and I like to combine it with RTC and interrupt driven. But perhaps I think too complicated ...
For a recurring appt, it's really no different. Once it is time for the appt, schedule a new one at the required time.

You could create an array of structs. Each struct would define when an event is to happen, and how long after that until the event repeats (0 would mean never), and what function to call when the even happens.

On each pass through loop(), iterate through the array to see if it is time to do something. If so, do it (by calling the appropriate function) and schedule the next occurrence.

I'd probably used a linked list, instead of an array, so there could be any number of events pending, and those that are not to happen again could be removed.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Tecnofago on Sep 18, 2015, 07:10 pm
Hello everybody.

I've been looking for an answer to my problem in both forums (English and Spanish) and I've found no solution.

What I need to do is to get time from a NTP server -which is easy to do- and show it with millisecond precision since I have to compare response times in a client-server system.

I looked over Time.h library and, although my programming kwnoledge is not much I concluded that it
doesn't support millisecond precision in time format.

If anybody knows how to solve my problem I'll be very grateful for their help.

Regards.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: odometer on Sep 18, 2015, 08:22 pm
In case I have only one appointment at 9:30 it is easy, but in case I have an recurring event every 15 minutes, a second one every hour, some daily and one weekly its getting complicate. So the TimeAlarms lib is nice and I like to combine it with RTC and interrupt driven. But perhaps I think too complicated ...
Each time you check the time, use a variable to "remember" it for next time. Or you can use multiple variables, such as one for the hours and one for the minutes. The reason you want to remember the time is so that you can tell when the time has changed.

Have the minutes changed? If so, are the new minutes equal to 0, or 15, or 30, or 45? If they are, then it is time to perform the "once every 15 minutes" activity. You might also want to perform the "once an hour" activity at one of these four times, or else at another time which is convenient to you, such as 5 minutes past the hour. You can also check the hour and see if it is the correct hour for the "once per day" activity.

So your code might look something like this:

Code: [Select]

int h_now; // hours now
int m_now; // minutes now
int m_old; // the "old" minutes

void setup() {
  // initial setup for the "old" minutes
  m_old = minute();
  
  // check the time right now  
  m_now = minute(); // minutes now
  h_now = hour();   // hours now
}

void loop() {
  // check the time right now
  m_now = minute();
  h_now = hour();
  
  // has the minute changed?
  if (m_now != m_old) {
    // if we're in here, then the minute has changed,
    // so now we check if it is time to do something
    
    if ((m_now==0) || (m_now==15) || (m_now==30) || (m_now==45)) {
      // we end up in here exactly once every 15 minutes
      // so here you put the code you want to run only once every 15 minutes
    }
    
    if (m_now==5) {
      // we end up here once an hour (at 5 minutes past the hour)
      // so here you put the code you want to run once an hour
    }
    
    if ((h_now==9) && (m_now==30)) {
      // we end up here once a day, at 9:30 a.m.
      // so here goes the stuff you want to happen daily at 9:30 a.m.
    }
    
    // finally, we update the "old" minutes for next time through the loop
    m_old = m_now;
  }
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: odometer on Sep 18, 2015, 08:26 pm
Hello everybody.

I've been looking for an answer to my problem in both forums (English and Spanish) and I've found no solution.

What I need to do is to get time from a NTP server -which is easy to do- and show it with millisecond precision since I have to compare response times in a client-server system.

I looked over Time.h library and, although my programming kwnoledge is not much I concluded that it
doesn't support millisecond precision in time format.

If anybody knows how to solve my problem I'll be very grateful for their help.

Regards.
What kind of Arduino board are you using? It makes a big difference here.

In what format do you get the time from this NTP server? Please give an example.

You might need to make special, "custom-made" functions to do what you want to do. But depending on the board, this might be easier or harder.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Tecnofago on Sep 20, 2015, 05:52 pm
What kind of Arduino board are you using? It makes a big difference here.

In what format do you get the time from this NTP server? Please give an example.

You might need to make special, "custom-made" functions to do what you want to do. But depending on the board, this might be easier or harder.
Hello odometer,

I'm using an Arduino UNO R3.

I haven`t built the sketch that gets time from a NTP server (using time library) yet because I don't know how to do it with my WIFI shield.

I have a WIFI Shield V1.1 (Seeed Studio), that uses a Roving Networks WIFI RN171 module, and by means of this code:

Quote
#include <WiFlyHQ.h>
#include <eHealth.h>
#include "Settings.h"
#include <SoftwareSerial.h>

SoftwareSerial wifiSerial(2,3);

WiFly wifly;

char buf[32];
String User_Agent;
long n;
long int uptime;
char timezone;
long int rtc;
char MyTime[20];
 
void setup()
{
    Serial.begin(115200);
    Serial.println("Comienza SincronizaNTP");
    Serial.print("Memoria libre: ");
    Serial.println(wifly.getFreeMemory(),DEC);
    
    wifiSerial.begin(9600);
    if (!wifly.begin(&wifiSerial, &Serial)) {
        Serial.println("Fallo al arrancar WiFly");
        terminal();
    }

     wifly.setTimeAddress("129.6.15.28");
     wifly.setTimePort(123);
     wifly.setTimezone(22);
     wifly.setTimeEnable(1);
     wifly.time();
     wifly.save();
     delay(100);
    
     wifly.getTime(MyTime, 20);
     uptime = wifly.getUptime();
     timezone = wifly.getTimezone();
     rtc = wifly.getRTC();

     Serial.print("uptime: ");
     Serial.println(uptime);
     Serial.print("timezone: ");
     Serial.println(timezone);
     Serial.print("rtc: ");
     Serial.println(rtc);
  
     Serial.println(MyTime);
    n=0;
}

I get the server NTP time in HH:MM:SS format. In fact, a pair of real values of rtc and MyTime variables are:

rtc: 1442763789
17:43:06


Thanks in advance.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: odometer on Sep 20, 2015, 07:37 pm

I get the server NTP time in HH:MM:SS format. In fact, a pair of real values of rtc and MyTime variables are:

rtc: 1442763789
17:43:06


Thanks in advance.
So, you only get the server time to the nearest second, but you want to display milliseconds. Yes, that is a problem.

Also:
rtc: 1442763789
17:43:06

That is another problem.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Tecnofago on Sep 26, 2015, 05:57 pm
Also:
rtc: 1442763789
17:43:06

That is another problem.
Sorry for answering so late but I'm only able to test my prototype on weekends.

I think that's not a problem because according to the sketch, wifly.getTime(MyTime, 20); is executed before rtc = wifly.getRTC(); so the norm is rct value is greater than MyTime value. I have experienced that the difference between those two values ranges from 1 to 3 seconds.

Appart from that, do you think it would be possible to get the server time to the nearest millisecond with any time library?

Thanks a lot!

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: odometer on Sep 27, 2015, 12:23 am
Appart from that, do you think it would be possible to get the server time to the nearest millisecond with any time library?

Does the server even give the time to the nearest millisecond?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Tecnofago on Sep 27, 2015, 05:50 pm
Does the server even give the time to the nearest millisecond?
That's a good question!

I don't know if the server gives the time to the nearest millisecond. I would have to figure it out.

Thanks for your response.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: absbrain on Oct 14, 2015, 10:15 pm
Question:
 in my application I'm using sim900 GSM modul and I set the time in setup (from GSM network) and that's it. No real rtc and I don't plan to use it. How accurate is the "virtual" arduino clock ?
I expect my arduino to work without reset for 2-3 months, so I'm hoping that I will have arduino virtual clock accuracy at least within seconds ?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Stewart-G0LGS on Oct 15, 2015, 07:14 pm
It appears that there is an issue with the Time library loosing time by several minutes a day (at least it does in my code).

I'm guessing that this is because my code uses the delay() function and the Time library uses the millis() function which do not work well together.

Perhaps using the micros() function in place of millis() will fix this.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Oct 15, 2015, 07:28 pm
If you do not have an RTC or another method of obtaining the real time then you can expect the Arduino not to keep very good time because it depends on the accuracy of the resonator or crystal used.  If you are worried that the delay() function is causing problems then don't use it.

For more advice please post your code or a small but complete example that exhibits the problem.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Stewart-G0LGS on Oct 15, 2015, 08:15 pm
My code is reading the RTC from a SIM900 module to pass to SetTime or a function that reads the SIM900 RTC with setSyncProvider.

Even after a few minutes there is a noticeable difference between the real Time and that shown on LCD display connected to the Arduino.

I'm a bit busy now, but if I get time I'll see if I can re-produce the effect without including all the code and needing all the library for the SIM900.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: patrick_kiwi on Oct 26, 2015, 05:18 am
Is it possible to create a timeSpan object in the arduino time library.  Its so useful to be able to add or subtract time objects and timeSpan objects to get Time-Spans.  I replaced a DS1307 with a  DS3231.  Unfortunately the more accurate DS3231 currently uses the arduino Time library which doesn't employ timeSpan objects.

There is no such object in the arduino time library

void showTimeSpan(const char* txt, const TimeSpan& ts) {
    Serial.print(txt);
    Serial.print(" ");
    Serial.print(ts.days(), DEC);
    Serial.print(" days ");
    Serial.print(ts.hours(), DEC);
    Serial.print(" hours ");
    Serial.print(ts.minutes(), DEC);
    Serial.print(" minutes ");
    Serial.print(ts.seconds(), DEC);
    Serial.print(" seconds (");
    Serial.print(ts.totalseconds(), DEC);
    Serial.print(" total seconds)");
    Serial.println();
}

 
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Oct 26, 2015, 08:03 am
Quote
Its so useful to be able to add or subtract time objects and timeSpan objects to get Time-Spans.
If you hold times in Unix time format then they can be added and subtracted to derive time spans.  Have a look at the makeTime() method in the Time library
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: odometer on Oct 26, 2015, 08:03 pm
Question:
 in my application I'm using sim900 GSM modul and I set the time in setup (from GSM network) and that's it. No real rtc and I don't plan to use it. How accurate is the "virtual" arduino clock ?
I expect my arduino to work without reset for 2-3 months, so I'm hoping that I will have arduino virtual clock accuracy at least within seconds ?
Over long periods, the Arduino's timekeeping is about what you would get from an old, wind-up alarm clock, meaning: if you just want to make something happen at approximately the correct time a few hours from now, then OK; but if you are going to run it for weeks on end without resetting the time, not OK.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: BagOfBones on Oct 28, 2015, 05:16 pm
Code: [Select]

#include <Time.h>
#include <TimeAlarms.h>

const int FanPin = 5;
const int PumpPin = 13;

AlarmId myTimer = Alarm.timerRepeat(5, FanOn);
AlarmId myTimer1 = Alarm.timerRepeat(10, FanOff);

void setup(){
  pinMode(PumpPin,OUTPUT);
  pinMode(FanPin,OUTPUT);
  Serial.begin(9600);

///SET TIME&DATE///

  setTime(00,00,00,31,10,15);

///ALARMS///

  Alarm.alarmOnce(0,00,01,AM1);
//  Alarm.alarmOnce(0,00,30,AM11);
//  Alarm.alarmOnce(0,01,00,AM2);
//  Alarm.alarmOnce(0,01,30,AM22);
//  Alarm.alarmOnce(00,02,00,PM1);
//  Alarm.alarmOnce(00,02,30,PM11);
//  Alarm.alarmOnce(00,03,00,PM2);
//  Alarm.alarmOnce(00,03,30,PM22);
}

///LOOP///

void loop(){
  digitalClockDisplay();
  Alarm.delay(1000);
}

///PUMP ON&OFF///

void AM1(){
  Serial.println("PUMP ON");
  digitalWrite(PumpPin,HIGH);
  Alarm.enable(myTimer);
  Alarm.enable(myTimer1);
  if (second() == 6 ){
    Serial.println("FECK");
  }
}
//void AM11(){
//  Serial.println("PUMP OFF");
//  digitalWrite(PumpPin,LOW);
//  Alarm.disable(myTimer);
//  Alarm.disable(myTimer1);
//}
//void AM2(){
//  Serial.println("PUMP ON");
//  digitalWrite(PumpPin,HIGH);
//  if(digitalRead(PumpPin) == HIGH){
//    Alarm.enable(myTimer);
//    Alarm.enable(myTimer1);
//  }
//}
//void AM22(){
//  Serial.println("PUMP OFF");
//  digitalWrite(PumpPin,LOW);
//  if(digitalRead(PumpPin) == LOW){
//    Alarm.disable(myTimer);
//    Alarm.disable(myTimer1);
//  }
//}
//void PM1(){
//  Serial.println("PUMP ON");
//  digitalWrite(PumpPin,HIGH);
//  if(digitalRead(PumpPin) == HIGH){
//    Alarm.enable(myTimer);
//    Alarm.enable(myTimer1);
//  }
//}
//void PM11(){
//  Serial.println("PUMP OFF");
//  digitalWrite(PumpPin,LOW);
//  if(digitalRead(PumpPin) == LOW){
//    Alarm.disable(myTimer);
//    Alarm.disable(myTimer1);
//  }
//}
//void PM2(){
//  Serial.println("PUMP ON");
//  digitalWrite(PumpPin,HIGH);
//  if(digitalRead(PumpPin) == HIGH){
//    Alarm.enable(myTimer);
//    Alarm.enable(myTimer1);
//  }
//}
//void PM22(){
//  Serial.println("PUMP OFF");
//  digitalWrite(PumpPin,LOW);
//  if(digitalRead(PumpPin) == LOW){
//    Alarm.disable(myTimer);
//    Alarm.disable(myTimer1);
//  }
//}

///FAN ON&OFF///

void FanOn(){
  Serial.println("FAN ON");
  digitalWrite(FanPin,HIGH);
}
void FanOff(){
  Serial.println("FAN OFF");
  digitalWrite(FanPin,LOW);
}

///DIGITAL CLOCK DISPLAY///

void digitalClockDisplay(){
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.println();
}
void printDigits(int digits){
  Serial.print(":");
  if(digits < 10)
    Serial.print('0');
    Serial.print(digits);
}


Explanation of project:

I've been stuck on this for a few days now, I've tried a few different methods but no progress.

I'm trying to turn a pump on 4 times a day for 1 hour each, using the "Alarm.alarmOnce()" function. It's currently set to minute intervals so that I can test it without waiting for a day to see if it works.

A fan should turn on and off every 5 seconds, whilst the pump is on. I've done this in a weird way, some of you will notice, it works well enough for what I'm trying to do and It's not a problem at this point in time.

The end result I want is a 24 hour clock, with alarms that turn on 4 times a day for one hour each, with a fan turning on & off every 5 seconds, at the end of the day the 24 clock resets and starts again instantly.

The problem:

I now know that I can have a maximum of 6 alarms, so I'm trying to reduce the number of alarms by triggering void "AM1" which will turn the pump on for 1 hour.

Instead of having an alarm to trigger "AM11" to disable the "fan on" & "fan off" voids.

I was hoping to have an "if" statement or something else which will turn the pump off and stop the "fan on" and "fan off" void from triggering.

I've been looking at using the blink without delay example but can't seem to make it work.

Any suggestions of what I could do or what I'm doing wrong?

All help is appreciated


Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cattledog on Oct 28, 2015, 06:20 pm
You can set more than six alarms by modifying the TimeAlarms header file. You can also reconfigure the onlyOnce alarm when it is triggered.

From TimeAlarms readme.txt

Quote
Q: How many alarms can be created?
A: Up to six alarms can be scheduled. 
The number of alarms can be changed in the TimeAlarms header file (set by the constant dtNBR_ALARMS,
note that the RAM used equals dtNBR_ALARMS  * 11)

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
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: BagOfBones on Oct 28, 2015, 07:30 pm
THANKS!!

I actually solved the problem but reconfiguring the alarms and then figured out afterwards that I can change the number of alarms, but much appreciated.

I'm going to change the code again but for now it works.

Here is the new code for anyone who might have a similar issue...

Code: [Select]

#include <Time.h>
#include <TimeAlarms.h>

const int FanPin = 5;
const int PumpPin = 13;

AlarmId myTimer = Alarm.timerRepeat(5, FanControl);

///SETUP///

void setup(){
  pinMode(PumpPin,OUTPUT);
  pinMode(FanPin,OUTPUT);
  Serial.begin(9600);

///SET TIME&DATE///

  setTime(00,00,00,20,04,2015);

///ALARMS////

  Alarm.alarmOnce(01,00,00,AM1);
  Alarm.alarmOnce(03,00,00,AM2);
  Alarm.alarmOnce(05,00,00,PM1); 
  Alarm.alarmOnce(07,00,00,PM2);
  Alarm.disable(myTimer);
  Alarm.alarmOnce(23,59,59,RESET);
}

///LOOP///

void loop(){
  digitalClockDisplay();
  Alarm.delay(1000);
}

///PUMP CONTROL///

void AM1(){
  Alarm.alarmOnce(02,00,00,AM1);
  if (hour() == 1){
  Serial.println("PUMP ON");
  digitalWrite(PumpPin,HIGH);
  Alarm.enable(myTimer);
  }
  else{
    Serial.println("PUMP OFF");
    digitalWrite(PumpPin,LOW);
    Alarm.disable(myTimer);
  }
}

void AM2(){
  Alarm.alarmOnce(04,0,00,AM2);
  if (hour() == 3){
  Serial.println("PUMP ON");
  digitalWrite(PumpPin,HIGH);
  Alarm.enable(myTimer);
  }
  else{
    Serial.println("PUMP OFF");
    digitalWrite(PumpPin,LOW);
    Alarm.disable(myTimer);
  }
}

void PM1(){
  Alarm.alarmOnce(06,00,00,PM1);
  if (hour() == 5){
  Serial.println("PUMP ON");
  digitalWrite(PumpPin,HIGH);
  Alarm.enable(myTimer);
  }
  else{
    Serial.println("PUMP OFF");
    digitalWrite(PumpPin,LOW);
    Alarm.disable(myTimer);
  }
}

void PM2(){
  Alarm.alarmOnce(8,00,00,PM2);
  if (hour() == 7){
  Serial.println("PUMP ON");
  digitalWrite(PumpPin,HIGH);
  Alarm.enable(myTimer);
//  Alarm.enable(myTimer1);
  }
  else{
    Serial.println("PUMP OFF");
    digitalWrite(PumpPin,LOW);
    Alarm.disable(myTimer);
//    Alarm.disable(myTimer1);
  }
}

///FAN CONTROL///

void FanControl(){
  if (second() %10 == 0){
  Serial.println("FAN ON");
  digitalWrite(FanPin,HIGH);
  }
  else if (second() %5 == 0){
    Serial.println("FAN OFF");
    digitalWrite(FanPin,LOW);
    }
}

///RESET///

void RESET(){
  setTime(00,00,00,20,04,2015);
}

///DIGITAL CLOCK DISPLAY///

void digitalClockDisplay(){
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.println();
}
void printDigits(int digits){
  Serial.print(":");
  if(digits < 10)
    Serial.print('0');
    Serial.print(digits);
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Clemens on Nov 21, 2015, 11:45 pm
Is it possible to use TimeAlarms together with a power saving lib (e.g. LowPower or narcoleptic)? Or is there an other technique to have periodic events and sleep phases with TimeAlarms?

Btw. it would be nice to config a RTC with TimeAlarms for example the wakeup IRQ.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: odometer on Nov 22, 2015, 07:48 am
Explanation of project:

I've been stuck on this for a few days now, I've tried a few different methods but no progress.

I'm trying to turn a pump on 4 times a day for 1 hour each, using the "Alarm.alarmOnce()" function. It's currently set to minute intervals so that I can test it without waiting for a day to see if it works.
Which four times?

Quote
A fan should turn on and off every 5 seconds, whilst the pump is on. I've done this in a weird way, some of you will notice, it works well enough for what I'm trying to do and It's not a problem at this point in time.
Do you mean on for 5 seconds, then off for 5 seconds? (10 seconds for one on/off cycle)
Or should the whole cycle be 5 seconds?

Quote
The end result I want is a 24 hour clock, with alarms that turn on 4 times a day for one hour each, with a fan turning on & off every 5 seconds, at the end of the day the 24 clock resets and starts again instantly.
It helps if you can write the whole thing out on paper. Of course, the fan will turn on and off too many times for you to write the entire schedule, but if you write just a few, you will see patterns that can be used.

Also, the Time and TimeAlarms library are probably overkill for what you are doing. It is not as hard as you might think to "make your own clock".
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: odometer on Nov 22, 2015, 08:25 am
Here is a clock demo I just made:
Code: [Select]


void setup() {
  Serial.begin(9600); // or faster if you like
  Serial.println("Clock demo by odometer  2015-11-22");
  Serial.println("This IS NOT guaranteed to work.");
}

void loop() {

  // Here we declare the variables we need for our clock.
  static uint32_t thisSecond = 0UL; // micros() at beginning of the second
  static uint8_t hh=0, mi=0, ss=0; // current time (hours, minutes, seconds)
  static uint16_t dayNumber=1; // for in case we decide we want to count days

  // This next part makes our clock "tick" every second.
  if ((micros() - thisSecond) >= 1000000UL) {
    // time for the next second
    thisSecond += 1000000UL;
    ss++;
    // sixty seconds make a minute, etc.
    if (ss>=60) { ss-=60; mi++; }
    if (mi>=60) { mi-=60; hh++; }
    if (hh>=24) { hh-=24; dayNumber++; }
    // and that's basically all we need to make our clock run!
   
    // This shows the time on the serial monitor every second.
    // (If you don't want to see the time every second, just comment it out.)
    Serial.print("Day ");
    Serial.print(dayNumber);
    Serial.print(", ");
    if (hh<10) Serial.print("0");
    Serial.print(hh);
    Serial.print(":");
    if (mi<10) Serial.print("0");
    Serial.print(mi);
    Serial.print(":");
    if (ss<10) Serial.print("0");
    Serial.print(ss);
  }
}

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Gadgetman9 on Nov 23, 2015, 01:10 am
I posted this problem in the Programming Questions forum, then found this thread.


I've been banging my head against the code for around at least a week now and can't get Alarm.write to work for a repeating alarm.  It will work for a timerRepeat, but not an alarmRepeat.

Why does the following work?
 Alarm.free(Alarm1On);
 Alarm1On=0;
 Alarm1On=Alarm.alarmRepeat(newTime, MorningAlarm);

 But this does not?
Alarm.write(Alarm1On, newTime);

I've tried using .enable (even though the source and header files show .write as enabling the ID)  and a disable/enable.

Does anyone know why .write doesn't work for alarmRepeat, but does for timerRepeat, or how to make it work for alarm.repeat? What am I doing wrong or not seeing here?

Code: [Select]
#include <Time.h>
#include <TimeAlarms.h>

AlarmID_t  Alarm1On, Alarm1Off;
byte cntr=0; // counter to stop setNewAlarmTime from running more than once

void setup()
{
  Serial.begin(9600);
  setTime(8,29,0,1,1,11); // set time to Saturday 8:29:00am Jan 1 2011

 
  // **************************************************************************************  create the  initial alarms
  Alarm1On=Alarm.alarmRepeat(8,29,2, MorningAlarm); 
  Alarm1Off=Alarm.alarmRepeat(8,29,5,EveningAlarm);
   
}

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


void setNewAlarmTime(){
 // create hour, minute and second variables, and another to string them together that will be useful to the TimeAlarms Library
 Serial.println(F("setNewAlarmTime tripped")); // serial print to tell if function actually tripped
time_t hrs, mins, secs, newTime;
hrs= 8;
mins=29;
secs=7;
newTime=AlarmHMS(hrs,mins,secs);



// ******************************************************** Set new on time
//************************************The next three lines work
 // Alarm.free(Alarm1On);
//  Alarm1On=0;
//  Alarm1On=Alarm.alarmRepeat(newTime, MorningAlarm);

// ******************The following line does not work
 Alarm.free(Alarm1On);
  Alarm.write(Alarm1On, newTime);

// **********************************************************Set new off alarm time
  secs=10;// push newTime's seconds from 7 to 10
  newTime=AlarmHMS(hrs,mins,secs);

 // Alarm.free(Alarm1Off);
 // Alarm1Off=1;
  //Alarm1Off=Alarm.alarmRepeat(newTime, EveningAlarm);
   Alarm.write(Alarm1Off, newTime);
 Serial.println(F("setNewAlarmTime ended and waiting for new alarms to trip")); // serial print to tell if function ended

}

// functions to be called when an alarm triggers:
void MorningAlarm(){
  Serial.print("Alarm1On tripped at ");
  Serial.print(hour());
  Serial.print(F(":"));
  Serial.print(minute());
  Serial.print(F(":"));
  Serial.println(second());
  }

void EveningAlarm(){
  Serial.print("Alarm1Off tripped at ");
  Serial.print(hour());
  Serial.print(F(":"));
  Serial.print(minute());
  Serial.print(F(":"));;
  Serial.println(second());
  Serial.println();
    if (cntr==0){ // This is only a test program.  Don't run setNewAlarmTime a second time
  setNewAlarmTime();   
  }
  else {
    Serial.println();
    Serial.println("Testing Complete");
  }
  cntr++;       
}














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);
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: odometer on Nov 23, 2015, 02:40 am
In my opinion, TimeAlarms is not good for much besides making your head hurt.

In most, if not all, cases, you get get around the supposed need for TimeAlarms with a bit of thought.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: bobkeyes on Dec 02, 2015, 01:06 am
Hello all. First post here. Tnx for all the good info, but I have a question.

I have a program,Arduino Uno, that will open a solenoid valve for a specific time at a predetermined time of day. I am doing it with TimeAlarms. It will be a stand alone program and it works well and does what I want it to do.

My problem is that sometimes I want to change the times in the alarm settings with a keypad. Can't figure out how to do that.

Here is a part of the code copied from several examples offered.

Any help MUCH appreciated. I am so new at this.

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

int drip1pin = 2;

void setup()
{
  Serial.begin(9600);
  while (!Serial) ; // wait until Arduino Serial Monitor opens
  setSyncProvider(RTC.get);   // the function to get the time from the RTC
  if(timeStatus()!= timeSet)
     Serial.println("Unable to sync with the RTC");
  else
     Serial.println("RTC has set the system time");     

    // create the alarms
 
  Alarm.alarmRepeat(12,47,00, Sprinkler1ONA);
  Alarm.alarmRepeat(12,47,10, Sprinkler1OFFA);
  Alarm.alarmRepeat(12,47,15, Sprinkler1ONB);
  Alarm.alarmRepeat(12,47,20, Sprinkler1OFFB);
  Alarm.alarmRepeat(12,47,25, Sprinkler1ONC);
  Alarm.alarmRepeat(12,47,30, Sprinkler1OFFC);
 // 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
  pinMode(9, OUTPUT);
  pinMode(2, OUTPUT);
}

void  loop(){ 
  if (timeStatus() == timeSet) {
    digitalClockDisplay();
  } else {
    Serial.println("The time has not been set.  Please run the Time");
    Serial.println("TimeRTCSet example, or DS1307RTC SetTime example.");
    Serial.println();
    delay(4000);
  }
  delay(1000);
  digitalClockDisplay();
  Alarm.delay(1000); // wait one second between clock display
}

// functions to be called when an alarm triggers:
void Sprinkler1ONA(){
  digitalWrite (drip1pin, HIGH);
}
void Sprinkler1OFFA(){
  digitalWrite (drip1pin, LOW); 
}
void Sprinkler1ONB(){
  digitalWrite (drip1pin, HIGH); 
}
  void Sprinkler1OFFB(){
  digitalWrite (drip1pin, LOW); 
}
void Sprinkler1ONC(){
  digitalWrite (drip1pin, HIGH); 
}
  void Sprinkler1OFFC(){
  digitalWrite (drip1pin, LOW); 
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: odometer on Dec 02, 2015, 01:52 am
Hello all. First post here. Tnx for all the good info, but I have a question.

I have a program,Arduino Uno, that will open a solenoid valve for a specific time at a predetermined time of day. I am doing it with TimeAlarms. It will be a stand alone program and it works well and does what I want it to do.
It does what you want it to do? Good for you.

Quote
My problem is that sometimes I want to change the times in the alarm settings with a keypad. Can't figure out how to do that.
OK, so it doesn't quite do what you want to do, after all.

The problem is, a "small" change can sometimes be a not-so-small amount of work. Like if you want to enlarge a doorway, but there is a load-bearing beam in the way. Oops, should have thought of that before you put the doorway in.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: larryd on Dec 02, 2015, 02:31 am
Free the alarm ID then create the new alarm as needed.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: bobkeyes on Dec 02, 2015, 05:11 am
It does what you want it to do? Good for you.
OK, so it doesn't quite do what you want to do, after all.

The problem is, a "small" change can sometimes be a not-so-small amount of work. Like if you want to enlarge a doorway, but there is a load-bearing beam in the way. Oops, should have thought of that before you put the doorway in.
Thanks for your help. I'll keep that in mind!
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: bperrybap on Dec 02, 2015, 06:26 am
t is the time the Arduino restarted. Is that reasonable? You are comparing apples and oranges here. The hour() extracts the hour portion of the time_t structure. You are comparing that to a time_t (which is the wrong type) structure.
not quite.
a time_t value is actually just an integer number. It is not not a structure. It does not contain any elements like hour, minute, year, month, etc....
The number represents a number of seconds since a particular point in time (an Epoch).
The most common point in time or Epoch is Jan 1, 1970 12:00 am which is used in all unix operating systems. The Time library is based on the unix time library.

The reason the comparison code was not working is that the Time library functions like hour(time_t) convert the epoch time integer value to a local time and then extracts the hour component.
So if you do hour(9) for example, you don't get nine since hour(9) is asking for what hour is it 9 seconds after Jan 1, 1970 12:00  which is 12 as that is the hour 9 seconds after midnight on Jan 1, 1970 which is the epoch.

--- bill


Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Prithul on Jan 09, 2016, 08:35 am
Hello! I am Prithul. I am 13 years old(yes I am noob). My question is -

1) How can I change the alarm time using a button?
2) Is it possible to set the time from my computer automatically using the Time library?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Jan 09, 2016, 08:46 am
(1) Do you know how to read the input from a button and cause the input to change the value of a variable ?
(2) No, but you could use a Real Time Clock (RTC) connected to the Arduino.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: bperrybap on Jan 09, 2016, 09:32 am
(2) No, but you could use a Real Time Clock (RTC) connected to the Arduino.
Actually you can. Code can use the __TIME__  and __DATE__ strings as constants and the have code that parses them to set the datetime in the Time library.

I do this in an example sketch that is included in my openGLCD library that shows how to display the date and time for a CLOCK on the glcd display without an RTC that automatically sets itself to the current local time on the PC.

The  issue is that the date and time are the date and time the code was compiled.
So it will be very close to the time the code is uploaded and run assuming it is compiled and immediately uploaded.
So while it can set the time to the current time when uploaded, if the Arduino is reset or powered off and back up again the sketch will reset the time back to that same time.

This method of setting the time is most useful for initially setting the time inside an RTC.

Once the datetime is set in the RTC, your sketch can use the RTC to set the time in the Time library as UKHeliBob recommended.
This method is better is it will be correct when the Arduino is reset or power cycled since the RTC keeps track of time when the power is off.

--- bill
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Jan 09, 2016, 09:43 am
Quote
The  issue is that the date and time are the date and time the code was compiled.
Which is why I didn't suggest using them.  The OP was not specific but I suspect that he wants to be able to set the Arduino to the current date and time.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: gustijuandi on Mar 03, 2016, 10:18 am
How To Fix ? Time.h   :(

(http://s29.postimg.org/3o5m45fon/error.jpg)

http://s22.postimg.org/6azl70zb5/error2.jpg

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: aarg on Mar 03, 2016, 10:22 am
Your library is not installed correctly. This post doesn't belong in this thread.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Mar 03, 2016, 11:18 am
It is said that a picture is worth a thousand words but that is not true in the case of code.
Much better to post the code that causes the error (in code tags) along with the error message(s).  The "Copy error messages" button is a clue.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: electronica_ang on Mar 06, 2016, 03:30 am
I have to mesure 10 hour periods with my arduino, but it has no connection to a computer or internet, i first try to make it with a simple millis(); compare, but recently i have a problem because millis(); somehow have reset itself (honestly i know it will happen someday, it wont count to infinite xD).
Is there a way to make arduino count date and time with its internal clock? or maybe is there any additional hardware that do it without internet or computer connection?

regards,
ANG.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: aarg on Mar 06, 2016, 03:50 am
I have to mesure 10 hour periods with my arduino, but it has no connection to a computer or internet, i first try to make it with a simple millis(); compare, but recently i have a problem because millis(); somehow have reset itself (honestly i know it will happen someday, it wont count to infinite xD).
Is there a way to make arduino count date and time with its internal clock? or maybe is there any additional hardware that do it without internet or computer connection?

regards,
ANG.
millis() doesn't just reset itself. You have some kind of software or hardware bug.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: CrossRoads on Mar 06, 2016, 05:11 am
Here's a simple count up timer:
Code: [Select]

unsigned long currentMicros;
unsigned long previousMicros;
unsigned long elapsedTime;

byte hundredths;
byte tenths;
byte secondsOnes;
byte oldSecondsOnes;
byte secondsTens;
byte minutesOnes = 1;
byte minutesTens = 3;
byte hoursOnes = 1;
byte hoursTens = 0;

void setup(){

  Serial.begin(115200); // make serial monitor match
  currentMicros = micros();
  previousMicros = currentMicros;
  Serial.println ("Setup Done");
}

void loop(){

  currentMicros = micros();

  // how long's it been?
  elapsedTime = currentMicros - previousMicros;
  //Serial.print ("Elapsed: ");  
  //Serial.println (elapsedTime);
  if ( elapsedTime >=10000UL){  // 0.01 second passed? Update the timers
    elapsedTime = 0;
    previousMicros  = previousMicros + 10000UL;
    hundredths = hundredths+1;
    if (hundredths == 10){
      hundredths = 0;
      tenths = tenths +1;
      if (tenths == 10){
        tenths = 0;
        secondsOnes = secondsOnes + 1;
        if (secondsOnes == 10){
          secondsOnes = 0;
          secondsTens = secondsTens +1;
          if (secondsTens == 6){ 
            secondsTens = 0;
            minutesOnes =  minutesOnes + 1;
            if (minutesOnes == 10){
              minutesOnes = 0;
              minutesTens = minutesTens +1;
              if (minutesTens == 6){
                minutesTens = 0;
                hoursOnes = hoursOnes +1;
                if (hoursOnes == 10){
                  hoursOnes = 0;
                  hoursTens = hoursTens =1;
                  if (hoursOnes == 4 && hoursTens ==2){
                    hoursOnes = 0;
                    hoursTens = 0;
                  }
                }
              } // minutesTens rollover check
            } // minutesOnes rollover check
          } // secondsTens rollover check
        } // secondsOnes rollover check
      } // tenths rollover check
    } // hundredths rollover check
  } // hundredths passing check



  if (oldSecondsOnes != secondsOnes){  // show the elapsed time
    oldSecondsOnes = secondsOnes;
    Serial.print ("Time: ");
    Serial.print (hoursTens);
    Serial.print(hoursOnes);
    Serial.print(":");
    Serial.print(minutesTens);
    Serial.print(minutesOnes);
    Serial.print(":");
    Serial.print(secondsTens);
    Serial.print(secondsOnes);
    Serial.print(" micros: ");
    Serial.println (currentMicros);

  } // end one second check

} // end loop
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Mar 06, 2016, 09:06 am
Quote
or maybe is there any additional hardware that do it without internet or computer connection?
You need a Real Time Clock aka an RTC
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: electronica_ang on Mar 10, 2016, 08:21 pm
Thank you so much CrossRoads!

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: hape on Mar 20, 2016, 02:14 pm
hi @all

i have done a program which reads the time out of a GPS device. The time is UTC and i'm from Germany so i want an easy way to correct this (including the date). So i searched and found this library.
But now the strange situation. The idea is to set the clock new if a GPS record is read. So it is possible that the internal clock goes ahead without setting from outside. But if this happens sometimes the hour is set to the original utc time and not to the time made by the setTime and adjustTime statement in the program.
In all other cases it works well.
Did someone know from this behavior?

hape
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Mar 20, 2016, 06:30 pm
I can see nothing wrong with the code that you have not posted.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: bperrybap on Mar 20, 2016, 06:58 pm
It sounds like you may be attempting to modify the actual time vs just offseting from the actaul time when converting the time to human readable local time format.
The proper way to deal with timezone offsets is to do an offset from the time_t value just before you convert the time_t value to human readable form, not by mucking with the actual time_t value being internally tracked.
i.e. the actual time is ALWAYS UTC and you do a shift only when converting to human form when needed.
That is the proper way to track time and convert to human readable local time.

The point of using a time_t epoch value was to ensure that the actual time was consistent everywhere and make time shifts like this super easy and accurate.
i.e. to shift by 3 hours in the future you simply add 3 hours of seconds to the time_t value.

To do a local time conversion, you fetch the time_t value, offset it as needed for the location conversion, and then use the functions that translate a time_t value to the needed human value like hour, min, month, etc....

That keeps everything simple and makes setting the time from something like a GPS, WWVB, NNTP, or other time system easy as you just push in the UTC time.

If you want a ready made library to help handling timezones as well as summertime adjustments, then consider using this library:
https://github.com/JChristensen/Timezone (https://github.com/JChristensen/Timezone)

--- bill
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: hape on Mar 21, 2016, 10:58 am
hi @all
@Bill: this sounds very good to me and i will give it a try. Yes i have meshed up these two instances of time and i did not understood (and i think its also not explained in the docu of the time library) for which reason the adjustTime command is implemented. After your nice explanation its totaly clear and i used the wrong way.
So after i changed the program at home i will post the result.
thx a lot for the nice help
hape

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: hape on Mar 21, 2016, 05:41 pm
hi @all and especially @Bill

now everything works like a charm (with the mentioned library and a local + utc time instance). I think i do know exactly whats going on.

But IMHO there is really a bug in the adjustTime routine.

now its:

void adjustTime(long adjustment) {       
        sysTime += adjustment;
}

but i think it has to be (and therefor many people are struggling with only sometimes adjustments)


void adjustTime(long adjustment){
        setTime(sysTime + adjustment);
}

what do you think?

thx a lot for your help

hape
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: bperrybap on Mar 21, 2016, 06:14 pm
The two are fairly similar but slightly different.
The adjustment routine does not affect the fractional part of a second or change when the next time sync occurs.

I'm not sure how that affects what you are seeing with time suddenly jumping.
Perhaps you are bumping into another issue.

I'm assuming you are running with a time sync provider.
If so, I don't see how that modification would fix things.
For example,
During initialization you set up a sync provider which gets the time from the GPS and sets the actual time_t time to UTC.

Then use adjustTime() to off the actual time for some timezone.

Keep in mind that the sync provider is not a 1 time thing. The Time library periodically calls it to keep the Arduino time in sync with the more accurate time provided by the sync provider.

So after the sync interval time period, the library will get the time from the GPS time provider again, and will once again set the time_t time to what is reported by the sync provider, if the sync provider provides UTC time, then the time_t time gets set to UTC.
At which point any adjustTime() offset is lost.


In my view a problem with the Time library is that it doesn't handle timezone offsets.
And perhaps a reason for this is the original Author, Michael Margolis, happens to live in the UTC timezone so timezone offsets were not needed for him. (kind of funny, but no so much for the rest of us)

--- bill
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: hape on Mar 21, 2016, 07:11 pm
hi @all

@Bill:
my thoughts: so if things happen fast in the Atmel the original statements sets the value for the sysTime but not the internal Clock. If than the internal clock gos up by one second and the set command comes afterward you have the wrong hour (the original). If you do it together it will work.

Look at this (so i'm not the only one struggling with this)

https://danricho.wordpress.com/2012/12/28/ds1307-real-time-clock-arduino/

https://github.com/kachok/arduino-libraries/issues/1

hape
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: bperrybap on Mar 21, 2016, 08:52 pm
Ok.
So I carefully went through the Time code to see what is happening.
This is an unintended side effect of incorrectly setting the time in a sync provider when modifying the time.

I believe that this is really a case of a sketch misusing the library more than an actual bug in the Time library.


It does involve the sync provider.

Here is what appears to be happening.

The sketch has enabled a sync provider but then the sketch code trying to modify the actual time rather than using a proper timezone offset.
Lots of people use this hack method for handling their timezone offsets - Even I've done this on occasion.

In this case, the sketch is trying to do the time adjustment with a sequence like:
Code: [Select]
 adjustTime(3600);                  // adjust onboard time by +3600 seconds (1hr) ***
    RTC.set(now());                    // sending the onboard time to the RTC.


Which is modifying the library time first and then trying to use the library time to set the sync provider time.

The problem with this is that the Time library did not assume people would be trying to modify the actual time this way, and adjustTime() does not adjust the sync provider schedule.
Using adjustTime() really doesn't make sense when using sync provider and that is why I call it a misuse of the library.
Think about it, why muck with the actual time in the library when the time should be coming correctly from a sync provider?
The sync provider should be providing the proper time.
That code sequence was assuming that now() returns a library time and not a time from a sync provider - which was a bad assumption.

Depending on the adjustment amount when adjusting forward (it only happens moving time forward) and where the sync interval is in its current cycle, it can cause the now() code to re-fetch the time from the sync provider. When it does that, the adjustment just made to the time in the library will be lost when used in a sequence like above since the now() code will be fetching the original unmodified time from the sync provider and setting the time in the library before it returns the time.
When a time provider sync occurs in now(), the pre-adjusted time is returned since that is what was returned by the sync provider.

The real answer is don't muck with and corrupt the real time and use timezone offsets properly.
However, for those that still do want to corrupt their actual time by mucking with the actual date and time they have a couple of choices:

Modify their sequence sequence to something like this:
Code: [Select]

t = now();
t += offset;
setTime(t);
RTC.set(t);


Alternatively, you could patch the code in adjustTime() to update the syncprovider time so an immediate call to now() does not call the sync provider like this:
(Assuming syncInterval is has not been set to zero)

Code: [Select]
void adjustTime(long adjustment) {
  sysTime += adjustment;
  nextSyncTime = sysTime + syncInterval;
}



In the big picture I'm not sure if the adjustTime() work around above should be added to the library code.
Theoretically the syncInterval could be set to zero and if it is, the sync provider is called every time and the original problem comes back again.

The issue is that the sketch turned on a sync provider and did not account for it being called in the sequence it used to set the RTC which involved using:
Code: [Select]
RTC.set(now());
Which cannot reliably be used to set the time in a sync provider.


Yes the library can usually work around what really is a bug in the sketch, but should it?
particularly since it can't in 100% of the cases.


--- bill


Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: hape on Mar 21, 2016, 09:14 pm
hi @all
@Bill: thx a lot for your research and explanation work. If i summarize your two posts (the first with the explanation why not using adjustTime for local time conversion and your last) i think you are right not to change the library. But i think there should be a change in documentation to explain clearly for which purpose the adjustTime command is.
I have followed your instruction and i'm really happy with the solution with the local and the UTC time. But i read a lot of docus and code before coding the program for my clock. But nobody explains the adjustTime command and the name of the command sounds if it was for making utc to another local time.

So thx a lot for all your posting and i hope that people who are searching for time library and adjustTime command read this because now i see it very clear what happens and why.

hape
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: bperrybap on Mar 21, 2016, 11:39 pm
Just a guess, but I'm guessing that adjustTime() existed before there was support for a sync provider.

I updated the playground page for the Time library to include a warning about using adjustTime() with a sync provider.


I think what would probably be useful would be to alter adjustTime() or add a new function like setTimeOffset() that stores an offset and applies it every time the time is fetched so it really could be used to create a timezone offset without having to modify the time in the sync provider.
Modifying the time in the sync provider isn't even possible in some cases, like with GPS, or WWVB signals which always use UTC.



--- bill
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: hape on Mar 22, 2016, 07:32 am
I updated the playground page for the Time library to include a warning about using adjustTime() with a sync provider.
OK thats good. I think also a hint like this (its your text)

"The proper way to deal with timezone offsets is to do an offset from the time_t value just before you convert the time_t value to human readable form, not by mucking with the actual time_t value being internally tracked.
i.e. the actual time is ALWAYS UTC and you do a shift only when converting to human form when needed.
If you want a ready made library to help handling timezones as well as summertime adjustments, then consider using this library:
https://github.com/JChristensen/Timezone"

would help a lot of people who get in touch with the time problem in the Arduino.

I'm sure that only < 1% of people want to update the sync provider time. Also i don't want it. It was a missunderstanding why i coded it this way.

So now ieverything goes in the right direction :-)

hape

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: aarg on Mar 22, 2016, 08:12 am
In my system, I bypass the sync provider arrangement due to specialized timing arrangements. I really only use the library for the useful macros and functions.

But if I were using the library as intended, both the sync provider and the millis() time maintained by the library would be UTC times.

It was very obvious to me that all the time functions had been overloaded mainly for the purpose of changing time, using the version that receives a time variable:
Code: [Select]
int     hour();            // the hour now
int     hour(time_t t);    // the hour for the given time


The issue is, that although it is easy to shift a time by creating a copy of now() and altering it with inline code, the new time will remain unaltered until the inline statements are executed again. Even if the time shift is contained in a function that modifies a global variable that functions like hour(time_t <variable>) will access, the same problem of "freshness" exists.

As it is currently structured, a sequence must be followed:
1. get current library time
2. add offset
3. use offset time for every applicable statement

However if a function has been created to make a time adjustment, the current time elements could be randomly accessed like this:

Code: [Select]
int hour = hour( UTCtoLocal(now()) );
or even without any function, like:
Code: [Select]
int hour = hour( now() + localTimeOffset);

As the library is written now, any of these simple methods will suffice. It appears as if the designers anticipated such usage. I think the problem is just that there are not enough solid examples of usage to make the design and the intention clear, so that the average user could easily utilize it.

An alternative is to internalize the local time offset, so that now() returns locally adjusted time (with no provision for DST), as in reply #497. The default would be zero. But unless it does fully support DST, it hardly seems worth the effort. It could also add to the confusion instead of helping to reduce it.  Maybe the ideas of Christensen's zone library could be simplified and incorporated to support only a single zone with DST?

Perhaps it would help if there were an example sketch included with the library to show how such time shifting can be handled.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: hape on Mar 22, 2016, 10:55 am
Maybe the ideas of Christensen's zone library could be simplified and incorporated to support only a single zone with DST?

Perhaps it would help if there were an example sketch included with the library to show how such time shifting can be handled.
Your first argument i didn't support. Everyone living in a 2 time zone (like in most countries in europe and america) will like to give a rule for changing the time (this is good in Christensen's zone library). Whats the other possibility: you have to change  the program every half year. That seems to me too complicated.

But your second argument is very good. If there is an example for time handling with and without timeshift i think everyone knows whats going on.

hape
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: aarg on Mar 22, 2016, 01:21 pm
Your first argument i didn't support. Everyone living in a 2 time zone (like in most countries in europe and america) will like to give a rule for changing the time (this is good in Christensen's zone library). Whats the other possibility: you have to change  the program every half year. That seems to me too complicated.

But your second argument is very good. If there is an example for time handling with and without timeshift i think everyone knows whats going on.

hape
I don't think a change from standard time to daylight savings time counts as a zone change. At least, I didn't mean it that way. I also hate changing the clocks, which is why I decided that all of my Arduino based clocks must do this automatically. If I live in the EST zone, it merely changes to EDT for half the year. In Christensen's library, there is one time zone rule that switches between EST and EDT. But it supports multiple time zone rules. Which is great, but perhaps not as easy to support as a single rule.

My idea was that the library could support a single zone with a single DST time change rule. But perhaps after all is said and done, it would be almost as difficult as supporting multiple zones. But as Christensen's library works well, maybe there is no point.

However, a fixed offset is very easy to implement, and some people might be content with flipping a software setting manually twice a year. It still would not require resetting the actual time, since that would still be in UTC. Even that does not have to be implemented in the actual library, since it is effectively just changing the offset by some minutes. That is a good compromise, where the fundamental functionality is there to either ignore, use to set a fixed zone (as for China), or use to set a dual zone, provided by some extra code in the application.

In fact, if such basic time adjustment functionality was part of the Time library, it would make it slightly easier to implement and use a full time zone library such as Christensen's. Mainly though, make it easy to choose from a range of convenient options.

But as I showed above, it is not terribly difficult to do it all at the application level with the existing library (except for implementing an automatic time zone change rule). I support the idea in reply #497, for a setTimeOffset() function, because it would make the application interface cleaner with the use of UTC time by centralizing the offset method.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: darnold on Apr 27, 2016, 07:17 pm
So, I would like to use Alarm.alarmRepeat like an alarm clock.  That is, the user (through a simple command line interface) can set the alarm to a particular time and can turn the alarm on and off.  I have the command line interface built and working and one of the commands is SLEEP where it takes a parameter of -t:hhmm as well as parameters for -n (alarm off) and -y (alarm on).  The handling for all this works fine.

My actual application is to send, at a user defined time every day, a "sleep packet" to a remote sensor and put it to sleep for a specified number of hours (-d:hh).  I would also like the user to be able to turn the alarm on and off at their discretion.

Having looked through the post and done a bit of simple testing it is not clear to me the best approach to setting, but more importantly changing the Alarm.alarmRepeat time.  I have tried Alarm.write(ID, newTime), where newTime is the user updated alarm time, but it doesn't seem to work--the updated alarm doesn't trigger.   

For subsequent changes to Alarm.alarmRepeat is the best approach to use Alarm.free(ID) and then a new alarm--i.e.,

Alarm.free(ID);
ID = Alarm.alarmRepeat(usrHour, usrMinute, 0, sendSleepPacket);

Just trying to determine what Alarm.write is for and what the best overall approach is for turning the alarm on and off and updating the time it triggers.   
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Apr 27, 2016, 07:47 pm
I assume that you are using an RTC in order to maintain accurate time.  If so, do you actually need to use the TimeAlarms library ?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: darnold on Apr 27, 2016, 08:07 pm
No, I am not.  I am using NTP to keep accurate time on the controller end of things (the coordinator) which is logging and publishing data from a set of remote sensors.  The remote sensors are solar powered and I am having the controller put them to sleep (so I don't have to have accurate clocks on the remote end).  The sketch is written so that the user, through a command line interface, can selectively decide which sensors to send to sleep, log data, etc.

I recognize that I could do it without the TimeAlarms library...but the work has been done and I would also like to know how to use it properly and I imagine others might as well (for this purpose).
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: bperrybap on Apr 27, 2016, 09:09 pm
The TimeAlarms library is definitely lacking in the documentation and example department.

From you description it isn't clear exactly what you have done.

The alarm code does some funky things and supports different types of alarms.

It sounds like you might actually be needing more than a single "alarm",
perhaps an alarm and a timer.
an alarm for the repeating event that occurs at the specific time every day.
a timer to handle the sleep function that is triggered by the alarm.



when you call alarmRepeat(H, M, S, func) the H:M:S is an offset from midnight.

The H:M:S is converted to a number of seconds and eventually converted to a time_t epoch.
If the offset from midnight last night has already passed, the time_t epoch will be after tonight upcoming midnight instead.

If you use the alarmRepeat() that uses a time_t value instead, the time_t can be either seconds from midnight or an actual future time_t time epoch value.

When you use write(ID, time_t) the time_t value is either an offset from midnight or a future time_t epoch value.

One issue that can arise is that of handling timezones.
If the person is entering times using H:M:S based on his local timezone and those values are used directly, it will obviously have issues as time is tracked tracked in UTC.

I think if you could provide more clarity on what you have done with either specific example code or specific examples of the functions and exact parameters used along with the resulting behavior, it would help figuring out what is happening.

--- bill


Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: darnold on Apr 27, 2016, 09:48 pm
You are right about the lack of documentation. 

In very simple terms and the best analogy is that of creating a function that works just like a beside alarm clock--i.e., I can set a time for the alarm clock to go off each day (and I of course can change that) and I can also turn the alarm off or on.

Currently I am doing the following:

// Function to put the Beecounter to sleep by setting a repeating Alarm
void sleepTimer (uint16_t inputTime) {
  uint8_t sleepHour;
  uint8_t sleepMinute;   

  sleepHour = int(inputTime / 100);
  sleepMinute = (inputTime - (sleepHour * 100));
  if ((sleepHour > 0) && (sleepHour < 25) && (sleepMinute >= 0) && (sleepMinute < 61)) {
    if (!sleepTime) {  // No previous alarm has been set
      repeatAlarm = Alarm.alarmRepeat(sleepHour,sleepMinute,0, sendSleepPacket);
    }
    else {  // Alarm exists so update it
      time_t newTime = AlarmHMS(sleepHour, sleepMinute, 0);
      //Alarm.write(repeatAlarm, newTime);
      Alarm.free(repeatAlarm);
      repeatAlarm = Alarm.alarmRepeat(sleepHour,sleepMinute,0, sendSleepPacket);     
    }
    sleepTime = inputTime; // update the global variable since a valid time has been entered
   }
  else {
    USBSerial.println(F("Invalid time parameter.  Must be in the format of HHMM using 24 hour clock."));
  }
}

...and this seems to work (I was originally trying to use Alarm.write).  Just not sure it is the best way of doing things. 

I don't need a timer on the controller end (just a daily alarm/trigger)...the controller just has to send a sleep packet to a remote sensor at a user specified time each day.  The remote sensor then puts itself in to sleep mode for a specified period of time, or duration that it receives in the sleep packet.  The sensor shuts things down (in this case an optical counter, an XBee,etc. and goes into power saving mode through a watchdog function...I don't need it to be super accurate on the remote side of things....just enough so that it doesn't run all night when the sun is not out.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: aarg on Apr 27, 2016, 10:44 pm
You have a strange notion of 24 hour time. This validation includes the time 24:60 and excludes the perfectly valid times 0:00-0:59.
Code: [Select]
if ((sleepHour > 0) && (sleepHour < 25) && (sleepMinute >= 0) && (sleepMinute < 61)) {
 You have a strange data schema where a 16 bit int holds the time in weird kind of 8 bit BCD. Here you cast an expression that has an uint16_t result to an int, and then assign it to a uint8_t. It may work, but it is redundant and confusing.
Code: [Select]
void sleepTimer (uint16_t inputTime) {
  uint8_t sleepHour;
  uint8_t sleepMinute;   

  sleepHour = int(inputTime / 100);


You should strip away the needless elaboration and use the simple functions from the library as they are implemented in TimeAlarmExample. The reason for the alarm time manipulation above is not clear without the rest of the code. But it seems to me, although I sympathize about the documentation (there is an opportunity for a great tutorial there!), that the problems you are having are more due to your use of the library, than the library itself.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: bperrybap on Apr 27, 2016, 10:53 pm
From what I can tell, what you have shown seems to look ok, but it isn't everything.

write(ID, time_t) checks the ID and, fills in the time value with the time_t value which you placed seconds since midnight, and calls enable()  which will convert that value to the real final epoch time time_t value.

alarmRepeat(hr, min, sec, func) calls create(time_t, func, IS_REPEAT, dtDailyAlarm) with time_t filled win the seconds since midnight, create()  checks to see if the time has been set, allocates an ID, fills in the alarm type information, fills in the alarm function, fills in the time value with the time_t (seconds since midnight in this case), and calls enable() to convert it to the real final epoch time time_t value.


What are the exact values being used that fail?
How is the time set & synced in the Time library and is there any altering of the time for timezones going on?
What does sendSleepPacket() do?

--- bill
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: bperrybap on Apr 27, 2016, 11:06 pm
aarg,
While agree that there are some strange and unneeded casts going on in the hour and min calculations, and a modulo calculation would probably have been better/simpler for the minutes,
I don't think the 16 bit time value is that bad.
I am assuming that the 16 bit value is probably being created from string input that takes the desired time as characters and converts it to a 16 bit number.

But in terms of the issue, it isn't clear to me that the issue is in the code we have seen so far.

darnold,
Can you provide a minimal/simple sketch that demonstrates the issue? Perhaps using some serial output prints.
This sketch should not need any external h/w as the sketch could set and initial dummy date/time in setup to initialize the time for the Time library.

This will allow others to be able to see the full code and build the sketch on their own h/w to repeat the results you are seeing.

--- bill
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: aarg on Apr 27, 2016, 11:21 pm
In #506, it says, "seems to work". So we can assume that there isn't an issue.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: darnold on Apr 28, 2016, 01:17 am
Thanks for pointing-out the issues with the input checks to see if a valid time parameter was passed.  I had bashed-out this function quite quickly in an effort to 'play' with the Alarm function and then got distracted when the Alarm.write method didn't appear to behave the way I had expected (and I had read others having a similar problem).  

And yes something like:
 sleepHour = inputTime / 100;
 sleepMinute = inputTime % 100;

is much cleaner.

The function is being passed a four digit number from a command line parser (eg., 2340).  So thus the need for uint16_t.

sendSleepPacket does pretty much what the function implies.  It sends an Xbee API sleep packet (I am using packets of various types) to a remote sensor that contains a simple integer value that causes the sensor to go into power saving mode for a specified period of time (the value of which is contained in the payload of the packet received).  And all this works just fine.

The bottom line was I posted my query since a number of the functions and methods in the TimeAlarms library are not well documented and I wanted to see what the correct way was of setting and turning on and off an alarm or alarms dynamically (versus statically which is what the examples basically demonstrate).

And as you said it is working...I just wanted to check whether I was using the library correctly/efficiently.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: bperrybap on Apr 28, 2016, 01:26 am
And as you said it is working...I just wanted to check whether I was using the library correctly/efficiently.
But that isn't what you said in post #502:
Quote
I have tried Alarm.write(ID, newTime), where newTime is the user updated alarm time, but it doesn't seem to work--the updated alarm doesn't trigger.    
From my looking at the TimeAlarms code, it appears that this should work.
It is lower overhead than freeing the timer ID and allocating a new one and filling it in with all the information.

I was going under the impression that the goal was to figure out why write() didn't seem to be doing what it is supposed to be doing.

And to figure that out, we need more information.

--- bill
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: darnold on Apr 28, 2016, 01:49 am
The function currently works using Alarm.free (as I have stated)....but I agree it should work, at least intuitively, using Alarm.write and would be more efficient.  However, it doesn't and what I mean by that is that it does not trigger an alarm that has been changed using this method.

If you troll through the 34 pages of this thread several people have raised this issue.  And mem (who I believe is the author of the library) suggests somewhere (20 or 30 pages back) to try using Alarm.free and Alarm.create.

But I thought I would ask the question since this seems a bit of an odd approach.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: bperrybap on Apr 28, 2016, 02:07 am
If you troll through the 34 pages of this thread several people have raised this issue.  And mem (who I believe is the author of the library) suggests somewhere (20 or 30 pages back) to try using Alarm.free and Alarm.create.

But I thought I would ask the question since this seems a bit of an odd approach.
That is a seemingly lazy response from Michael - I'm a bit surprised.
From looking at the code, using write() should work - and that seems to be its intended use.
If there really is an issue, it should be fixed.
It is obviously something very simple/trivial.

I'm still leaning towards something odd being done in the sketch vs the library; however,
this is where having a nice contained sketch that doesn't require any other h/w, that demonstrates the issue would be helpful.


If you can provide a sketch that demonstrates the issue, I'll track down the issue, fix it and get the changes put into Paul's git repository so that it becomes available to everyone through the library manager.


--- bill
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: bperrybap on Apr 28, 2016, 06:20 am
ok. So I created a test sketch to figure this out.
TimeAlarms is some very contorted code.
This issue is in the library.
At best this is an oversight but I would argue it is a bug that can easily be fixed.

Each alarm has a trigger time_t and this trigger time_t is updated to reflect when the alarm/timer should trigger and call the alarm function.
Each alarm also has a  "set" value that is used to calculate the trigger time_t
in the case of an explicit alarm the set value is moved directly to the trigger time_t
in the case of repeating alarms, it is much more tricky.
For  repeating alarms the set value is used to calculate the next trigger time_t and this is where the issue is.
This issue actually arises from a complex interaction of several functions do to the way repeating alarms are handled and the way the code is implemented.
The code that calculates the next trigger time_t makes the assumption that you will always want to set the alarm for a future time - which is a good assumption.
It uses a calculation to determine if the trigger time_t will be relative to last nights midnight or tomorrows midnight to determine if the alarm is for later today or for tomorrow.

enable() and disable() can be called at any time.
When enable() is called, the next trigger time_t must be re-calculated since an unknown amount of time has elapsed (it could have been days). So it calls the code to calculate the next trigger time_t. The code that calculates the next trigger time can't just blindly bump the trigger time_t when re-calculating for a repeating alarm.
The code assumes that if the trigger time_t is already in the future then it does not need to be re-calculated. If it is in the past, it re-calculates it determining if the alarm will be later today or tomorrow.
This is also ok.
HOWEVER...... This now interacts with the write() code.
The write() code modifies the alarm "set" value and then calls the enable(), assuming that enable() will take care of re-calculating the trigger time_t as that is what it does.
The issue that arises is that when an alarm is triggered, it also calls the code that updates the trigger time_t before it calls the alarm function.
So this means that when the alarm function is called, the trigger time_t will always reflect the next trigger time_t which means that it will be in the future.
But because the trigger time_t is in the future, when write() calls enable() which calls the code to update the trigger time_t, the code that calculates the next trigger time will not update the trigger time_t, since the existing trigger time_t will always be in the future. This means that the alarm time that write() was trying to modify will not take effect until *after* the next alarm triggers.
To me this is not the behavior that people expect and I do not believe that this was the intended behavior.

Now for the good part. This can be fixed with a single line of code.

In the function write()
change the code from this:
Code: [Select]
   // write the given value to the given alarm
    void TimeAlarmsClass::write(AlarmID_t ID, time_t value)
    {
      if(isAllocated(ID))
      {
        Alarm[ID].value = value;
        enable(ID);  // update trigger time
      }
    }

To this:
Code: [Select]
   // write the given value to the given alarm
    void TimeAlarmsClass::write(AlarmID_t ID, time_t value)
    {
      if(isAllocated(ID))
      {
        Alarm[ID].value = value;
        Alarm[ID].nextTrigger = 0; // clear out previous trigger time
        enable(ID);  // update trigger time
      }
    }


That will fix it.
This works by ensuring that the nextTrigger value which is the trigger time_t will always be in the past.
This is what create() does as part of creating a new alarm which is why it works when the alarm is re-created.
(Actually it is set to zero when free() is called)

I'll get with Paul to get this fix into the git repository so that the updated code will be available through the IDE library manager.
In the mean time just go update your code manually to add that one line of code.

--- bill





Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: darnold on Apr 28, 2016, 08:38 am
That's fantastic!  I woke up this morning to find the issue resolved, thanks Bill.  Despite some sloppy coding on my part I feel somewhat vindicated that my suspicion was right that the library was not behaving as expected (at least the way I would have thought the write function should behave).

Thanks again.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Apr 29, 2016, 08:09 am
How will the Arduino know that the device is turned on ?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: bperrybap on Apr 29, 2016, 08:06 pm
How will the Arduino know that the device is turned on ?
Huh? I'm not sure who this is directed to or what it is asking.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Apr 29, 2016, 11:13 pm
Huh? I'm not sure who this is directed to or what it is asking.
Me neither !
Sorry.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: aarg on Apr 30, 2016, 12:26 am
ok. So I created a test sketch to figure this out.
TimeAlarms is some very contorted code.
This issue is in the library.
Thanks. Karma given.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: lumarpe on May 17, 2016, 09:19 pm
Hi All, I'm starting a project to control the lights in 8 shelves with with different schedules. In each shelf lights will be on for about half the day. I started with a mega2560, serial connection to pc and TimeAlarms examples. Everything works fine except opening and closing the serial monitor resets the sketch in the board, is that normal and is there a way to avoid it?

Following is the code for just one shelf



Code: [Select]

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

#define TIME_HEADER  "T"   // Header tag for serial time sync message
#define TIME_REQUEST  7    // ASCII bell character requests a time sync message
const int ledShelf1 = 2;
void setup()
{
  pinMode(ledShelf1, OUTPUT);
  setTime(20,29,30,5,16,16); // set time to Saturday 8:29:00pm May 6 2016
  Alarm.alarmRepeat(20,30,10, Shelf1);  // 8:30:20 pm every day
  Alarm.alarmRepeat(20,30,20, Shelf1OFF);  // 8:30:20 pm every day
  Serial.begin(9600);
  Serial.println("Waiting for sync message");
  }
void  loop()
{  
   Alarm.delay(1000); // wait one second between clock display
   digitalClockDisplay();  
}
void digitalClockDisplay()
{
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print(" ");
  Serial.print(day());
  Serial.print(" ");
  Serial.print(month());
  Serial.print(" ");
  Serial.print(year());
  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);
}

// functions to be called when an alarm for shelf 1 triggers:
  void Shelf1(){
    Serial.println("Lights on in shelf 1");
    digitalWrite(ledShelf1, HIGH); // Lights on in shelf 1
    }    
  void Shelf1OFF(){
    Serial.println("Lights off in shelf 1");
    digitalWrite(ledShelf1, LOW); // Lights off in shelf 1
    }

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cattledog on May 17, 2016, 09:57 pm
Quote
opening and closing the serial monitor resets the sketch in the board, is that normal and is there a way to avoid it?
Yes, its normal behaviour, and the ways to change it are in here http://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection (http://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection)
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on May 17, 2016, 10:01 pm
Quote
I'm starting a project to control the lights in 8 shelves with with different schedules
Read the TimeAlarms readme.  You will need to increase the maximum number of alarms allowed.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: pjrc on Jul 07, 2016, 12:50 am
Today I applied several small fixes to TimeAlarms, and I did some general cleanup.  If anyone's still watching this thread and interested, please give the latest a try.

https://github.com/PaulStoffregen/TimeAlarms (https://github.com/PaulStoffregen/TimeAlarms)

I tested here and it seems to be working well.  Planning to release 1.5 (to Arduino's boards manager) soon.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: AviG on Aug 05, 2016, 08:36 pm
I am trying to print out the time every second, but it isn't working. Please help.
Code: [Select]

#include <Time.h>
#include <TimeLib.h>

void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.print("It is " + hour() + ':' + minute() + ':' + second());
  delay(1000);
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Aug 05, 2016, 08:47 pm
What does it do ?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Welsyntoffie on Aug 15, 2016, 02:12 am
Hi.
First all, nice library.
I want to know how can I change the alarm time during runtime.
If I have a variable...
Int hourset = 0
This variable will be able to change with a pushbutton +1 or -1.
If I do this... alarmrepeat(hourset,0,0, function) then the alarm does not trigger.
How can make this work?
I do not want to reprogram my arduino for a time alarm time. I have been looking at another thread that when dormant in 2010 but its still unclear to me.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Hassiebassie on Aug 27, 2016, 12:45 pm
Hi,
I'm having troubles using the time library.
I'm using the 1.6.11 SDK.

1st attempt:
At first I used the installer found on http://www.pjrc.com/teensy/td_libs_Time.html
(I downloaded the Beta, that's the one that supports 1.6.11).

It installed fine. My code won't compile:
#include <time.h>

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);      // open the serial port at 9600 bps:
  Serial.println("Running...");
}

int CurrentTime;

void loop() {
  // put your main code here, to run repeatedly:
  CurrentTime = now();
  Serial.println(CurrentTime);
  delay(1000);  // Wait a second
}

The error I get:
'now' was not declared in this scope

Seems to me that the library was not installed properly.


I Appreciate your help
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Aug 27, 2016, 12:48 pm
Code: [Select]
#include <time.h>Is the file called time.h or Time.h ?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Hassiebassie on Aug 27, 2016, 10:09 pm
Yep, that's it. I changed it to <Time.h>.
That solved this issue.
Thanks
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: RazielReaver on Sep 01, 2016, 12:11 am
there is anyway to send a variable in the alarms?? like in example


id[0] = Alarm.alarmRepeat(17,0,0, SensorperHour(0));
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Sep 01, 2016, 09:14 am
Are you wanting to get the ID of the alarm into a variable or use a variable as one of the alarm parameters ?

What have you tried ?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: questionerer on Nov 01, 2016, 12:12 pm
I use code from the TimeNTP example.

When I run a particularly frequent interrupt, the time freezes (for example stuck at same hours, minutes and seconds for a long time) until the interrupt becomes less frequent. But then the time is out of sync when the time resumes (starts from where it froze).

How to fix this?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Nov 01, 2016, 12:29 pm
Quote
How to fix this?
Make the interrupts happen less often, or make the interrupt handler faster.

Without your sharing your code, only you can do that.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: w8bh on Nov 17, 2016, 01:52 am
Has anyone had success with using the 1pps output of their GPS module to synchronize the time library? 

I built a GPS clock using the time library and tinyGPS.  The displayed time is always a fraction of a second late, because of a delay between the top of the second and parsing of the GPS data that follows it.

Has anyone used the 1pps line to trigger an interrupt?  And do you use it to set the time one second *beyond* the most-recently-decoded time?   Is there a better method?    Any tips would be appreciated.

Bruce.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: odometer on Nov 17, 2016, 03:32 am
Has anyone had success with using the 1pps output of their GPS module to synchronize the time library? 

I built a GPS clock using the time library and tinyGPS.  The displayed time is always a fraction of a second late, because of a delay between the top of the second and parsing of the GPS data that follows it.

Has anyone used the 1pps line to trigger an interrupt?  And do you use it to set the time one second *beyond* the most-recently-decoded time?   Is there a better method?    Any tips would be appreciated.

Bruce.
I have built several Arduino-based clocks. I have never used the Time library. Instead, I just "roll my own".

I've never used a GPS module, but assuming that that 1 PPS output always happens at the top of the second (does it?), then I just might use a trick like what you describe to get the time to within a fraction of a second. But I've also never used interrupts, and I have no idea if things like millis() and micros() play well with interrupts.

As far as the logic is concerned, once you know which second it is (from parsing a GPS signal), then there is no need to parse any further GPS signals: you can just count 1 PPS pulses, and Arduinos are very good at counting. Except if there's a leap second, in which case you will need to re-synchronize or something. But you only need to check for those once every 6 months.

tl;dr: Sounds like as good a method as any.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: karacayali on Nov 29, 2016, 07:31 pm
Hello,

I am trying to make a home automation system. I am using and Arduino Uno now and ordered a Mega. My aim is to control lamps, shades and heater with a web server as well as buttons on the walls. The project includes;
- A web server on Ethernet shield SD card
- XML and HTTP requests
- Scheduled tasks at certain intervals and also at specific times

I managed to run web server part alone. But when I tried to combine Time and TimeAlarm functions with web server code, it doesn't work. Nothing happens in loop section or it fails. For example below code works fine.


Code: [Select]
#include <TimeLib.h>

long previousMillis = 0;
unsigned long currentMillis = 0;
long interval = 5000;
String currentTime = "";

void setup() {
  setTime(8,25,5,8,1,2016); // hr,min,sec,day,month,yr);
  Serial.begin(9600);    
}

void loop() {
  
  currentMillis = millis();
  if(currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;
    
    currentTime = "";
    if (day()<10){ currentTime += String(0) + day(); }
      else { currentTime += day(); }
    if (month()<10){ currentTime += "." + String(0) + month(); }
      else { currentTime += "." + String(month()); }
    currentTime += "." + String(year()) + " ";
    if (hour()<10){ currentTime += String(0) + String(hour()); }
    else { currentTime += String(hour()); }
    if (minute()<10){ currentTime += ":" + String(0) + String(minute()); }
    else { currentTime += ":" + String(minute()); }
    if (second()<10){ currentTime += ":" + String(0) + String(second()); }
    else { currentTime += ":" + String(second()); }
    
    Serial.print("5 seconds passed. Time is: ");
    Serial.println(currentTime);
  }

}


Result:
5 seconds passed. Time is: 08.01.2016 08:25:10
5 seconds passed. Time is: 08.01.2016 08:25:15
5 seconds passed. Time is: 08.01.2016 08:25:20


But with web server code like below it doesn't work. Time alarms fails too. Can anyone help?


Code: [Select]
#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>
#include <TimeLib.h>

#define REQ_BUF_SZ   60    // size of buffer used to capture HTTP requests
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 200);
EthernetServer server(80);         // create a server at port 80
File webFile;                      // the web page file on the SD card
char HTTP_req[REQ_BUF_SZ] = {0};   // buffered HTTP request stored as null terminated string
char req_index = 0;                // index into HTTP_req buffer

int x;

long previousMillis = 0;
unsigned long currentMillis = 0;
long interval = 5000;
String currentTime = "";

void setup()
{

  setTime(8,25,5,8,1,2016); // hr,min,sec,day,month,yr);
  
  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);    // disable Ethernet chip
  
  // for debugging
  Serial.begin(9600);    
  Serial.println("Initializing SD card...");
  if (!SD.begin(4)) {
    Serial.println("ERROR - SD card initialization failed!");
    return;    // init failed
  }
  Serial.println("SUCCESS - SD card initialized.");
  if (!SD.exists("index.htm")) {
    Serial.println("ERROR - Can't find index.htm file!");
    return;  // can't find index file
  }
  Serial.println("SUCCESS - Found index.htm file.");
  
  Ethernet.begin(mac, ip);  // initialize Ethernet device
  server.begin();           // start to listen for clients
}

void loop()
{

  currentMillis = millis();
  if(currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;
    
    currentTime = "";
    if (day()<10){ currentTime += String(0) + day(); }
      else { currentTime += day(); }
    if (month()<10){ currentTime += "." + String(0) + month(); }
      else { currentTime += "." + String(month()); }
    currentTime += "." + String(year()) + " ";
    if (hour()<10){ currentTime += String(0) + String(hour()); }
    else { currentTime += String(hour()); }
    if (minute()<10){ currentTime += ":" + String(0) + String(minute()); }
    else { currentTime += ":" + String(minute()); }
    if (second()<10){ currentTime += ":" + String(0) + String(second()); }
    else { currentTime += ":" + String(second()); }
    
    Serial.print("5 seconds passed. Time is: ");
    Serial.println(currentTime);
  }
  
  EthernetClient client = server.available();  // try to get client
    
  if (client) {  // got client?
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {   // client data available to read
        char c = client.read(); // read 1 byte (character) from client
         if (req_index < (REQ_BUF_SZ - 1)) {        // -- limit the size of the stored received HTTP request -- buffer first part of HTTP request in HTTP_req array (string) - leave last element in array as 0 to null terminate string (REQ_BUF_SZ - 1)
          HTTP_req[req_index] = c;          // save HTTP request character
          req_index++;
        }
        if (c == '\n' && currentLineIsBlank) {     // last line of client request is blank and ends with \n -- respond to client only after last line received
          client.println("HTTP/1.1 200 OK");    // send a standard http response header
          if (StrContains(HTTP_req, "ajax_inputs")) {   // remainder of header follows below, depending on if web page or XML page is requested Ajax request - send XML file
            client.println("Content-Type: text/xml");   // send rest of HTTP header
            client.println("Connection: keep-alive");
            client.println();
            WebRoleCalistir();
            XMLGonder(client);       // send XML file containing input states
          }
          else {  // web page request
            client.println("Content-Type: text/html");       // send rest of HTTP header
            client.println("Connection: keep-alive");
            client.println();
            webFile = SD.open("index.htm");        // open web page file
            if (webFile) {
              while (webFile.available()) {
                client.write(webFile.read()); // send web page to client
              }
              webFile.close();
            }
          }
          
          Serial.print(HTTP_req);   // display received HTTP request on serial port
          req_index = 0;    // reset buffer index and all buffer elements to 0
          StrClear(HTTP_req, REQ_BUF_SZ);
          break;
        }
        
        if (c == '\n') {          // every line of text received from the client ends with \r\n
          currentLineIsBlank = true;    // last character on line of received text  // starting new line with next character read
        }
        else if (c != '\r') {
          currentLineIsBlank = false;     // a text character was received from client
        }
        
      } // end if (client.available())
    } // end while (client.connected())
    delay(1);      // give the web browser time to receive the data
    client.stop(); // close the connection
  } // end if (client)

  //AmpulKontrol();  
}


void StrClear(char *str, char length)     // sets every element of str to 0 (clears array)
{
  for (int i = 0; i < length; i++) {
    str[i] = 0;
  }
}


char StrContains(char *str, char *sfind)    // searches for the string sfind in the string str - returns 1 if string found - returns 0 if string not found
{
  char found = 0;
  char index = 0;
  char len;

  len = strlen(str);

  if (strlen(sfind) > len) {
    return 0;
  }
  while (index < len) {
    if (str[index] == sfind[found]) {
      found++;
      if (strlen(sfind) == found) {
        return 1;
      }
    }
    else {
      found = 0;
    }
    index++;
  }

  return 0;
}


void WebRoleCalistir(void)  
{

x = 4;

}


void XMLGonder(EthernetClient cl)    
{

  cl.print("<?xml version = \"1.0\" ?>");
  cl.print("<inputs>");

  cl.print("<states>");
    cl.print("x");
  cl.println("</states>");

  cl.print("</inputs>");
}



Result:
Initializing SD card...
SUCCESS - SD card initialized.
SUCCESS - Found index.htm file.
5 seconds passed. Time is:  
5 seconds passed. Time is:  
5 seconds passed. Time is:  
5 seconds passed. Time is:  
5 seconds passed. Time is:  
5 seconds passed. Time is:  
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Nov 29, 2016, 07:40 pm
Code: [Select]
    if (month()<10){ currentTime += "." + String(0) + month(); }
I have to wonder why you think that "." id OK in building the String, but "0" is not.

I have to wonder why you are pissing away resources on the String class, at all.

The SD class needs a 512 byte buffer to hold data to write to the card. On a Uno, that is 25% of the available memory. Other classes need memory, too. What do you suppose happens when there is not enough memory to allocate a String instance?

I have to wonder why you allow string literals to occupy SRAM:
Code: [Select]
            client.println("Content-Type: text/xml");   // send rest of HTTP header
            client.println("Connection: keep-alive");

Keep them out, with the F() macro.

            client.println(F("Content-Type: text/xml"));   // send rest of HTTP header
            client.println(F("Connection: keep-alive"));

Code: [Select]
              while (webFile.available()) {
                client.write(webFile.read()); // send web page to client
              }

Sending a packet containing one character is incredibly inefficient. Use an array, and read and send at least 32 characters per packet.

Fix those issues, and I'm betting that you'll save enough memory to allow the program to operate.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Welsyntoffie on Nov 30, 2016, 09:20 pm
Hello,

I am trying to make a home automation system.

Have you tried looking at using HMI software.
Like mango, reliance scada or FTview.
With a modbus library and an HMI you could do it very easy.
Connect your ethernet shield to a wifi router and check out HMI droid (also available for iphone). You can control your entire home from your phone.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: karacayali on Dec 03, 2016, 01:39 pm
I have to wonder why you think that "." id OK in building the String, but "0" is not.
Fixed.


The SD class needs a 512 byte buffer to hold data to write to the card. On a Uno, that is 25% of the available memory. Other classes need memory, too.
How much memory TimeAlarms library needs to run? I got my Mega. Timestamp worked with millis. But functions from TimeAlarms library don't work. I haven't included control codes yet. They work seperately. I will include them if I manage to run a Web server with Time alarms.

Sketch uses 23,314 bytes (9%) of program storage space. Maximum is 253,952 bytes.
Global variables use 1,627 bytes (19%) of dynamic memory, leaving 6,565 bytes for local variables. Maximum is 8,192 bytes.

Code: [Select]

#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>
#include <Time.h>
#include <TimeLib.h>
#include <TimeAlarms.h>

#define REQ_BUF_SZ   60    // size of buffer used to capture HTTP requests
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 200);
EthernetServer server(80);         // create a server at port 80
File webFile;                      // the web page file on the SD card
char HTTP_req[REQ_BUF_SZ] = {0};   // buffered HTTP request stored as null terminated string
char req_index = 0;                // index into HTTP_req buffer

int x;

long previousMillis = 0;
unsigned long currentMillis = 0;
long interval = 2000;
String currentTime = "";

void setup()
{

  setTime(8,25,53,8,1,2016); // hr,min,sec,day,month,yr);

  Alarm.alarmRepeat(8,26,0, MorningAlarm);  // 8:30am every day
  Alarm.timerRepeat(2, Repeats); 
 
  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);    // disable Ethernet chip
 
  // for debugging
  Serial.begin(9600);     
  Serial.println("Initializing SD card...");
  if (!SD.begin(4)) {
    Serial.println("ERROR - SD card initialization failed!");
    return;    // init failed
  }
  Serial.println("SUCCESS - SD card initialized.");
  if (!SD.exists("index.htm")) {
    Serial.println("ERROR - Can't find index.htm file!");
    return;  // can't find index file
  }
  Serial.println("SUCCESS - Found index.htm file.");
   
  Ethernet.begin(mac, ip);  // initialize Ethernet device
  server.begin();           // start to listen for clients
}

void loop()
{

//  currentMillis = millis();
//  if(currentMillis - previousMillis > interval) {
//    previousMillis = currentMillis;
//    timee();
//  }
 
  EthernetClient client = server.available();  // try to get client
   
  if (client) {  // got client?
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {   // client data available to read
        char c = client.read(); // read 1 byte (character) from client
         if (req_index < (REQ_BUF_SZ - 1)) {        // -- limit the size of the stored received HTTP request -- buffer first part of HTTP request in HTTP_req array (string) - leave last element in array as 0 to null terminate string (REQ_BUF_SZ - 1)
          HTTP_req[req_index] = c;          // save HTTP request character
          req_index++;
        }
        if (c == '\n' && currentLineIsBlank) {     // last line of client request is blank and ends with \n -- respond to client only after last line received
          client.println("HTTP/1.1 200 OK");    // send a standard http response header
          if (StrContains(HTTP_req, "ajax_inputs")) {   // remainder of header follows below, depending on if web page or XML page is requested Ajax request - send XML file
            client.println(F("Content-Type: text/xml"));   // send rest of HTTP header
            client.println(F("Connection: keep-alive"));
            client.println();
            WebRoleCalistir();
            XMLGonder(client);       // send XML file containing input states
          }
          else {  // web page request
            client.println(F("Content-Type: text/html"));       // send rest of HTTP header
            client.println(F("Connection: keep-alive"));
            client.println();
            webFile = SD.open("index.htm");        // open web page file
            if (webFile) {
              while (webFile.available()) {
                client.write(webFile.read()); // send web page to client
              }
              webFile.close();
            }
          }
         
          Serial.print(HTTP_req);   // display received HTTP request on serial port
          req_index = 0;    // reset buffer index and all buffer elements to 0
          StrClear(HTTP_req, REQ_BUF_SZ);
          break;
        }
       
        if (c == '\n') {          // every line of text received from the client ends with \r\n
          currentLineIsBlank = true;    // last character on line of received text  // starting new line with next character read
        }
        else if (c != '\r') {
          currentLineIsBlank = false;     // a text character was received from client
        }
       
      } // end if (client.available())
    } // end while (client.connected())
    delay(1);      // give the web browser time to receive the data
    client.stop(); // close the connection
  } // end if (client)

  //AmpulKontrol(); 
}

void MorningAlarm() {
  Serial.println("Alarm: - MorningAlarm");
  timee();
}

void Repeats() {
  Serial.println("Repeats");
  timee();
}


void timee() {

    currentTime = "";
    if (day()<10){ currentTime += "0" + String(day()); }
      else { currentTime += String(day()); }
    if (month()<10){ currentTime += ".0" + String(month()); }
      else { currentTime += "." + String(month()); }
    currentTime += "." + String(year()) + " ";
    if (hour()<10){ currentTime += "0" + String(hour()); }
    else { currentTime += String(hour()); }
    if (minute()<10){ currentTime += ":0" + String(minute()); }
    else { currentTime += ":" + String(minute()); }
    if (second()<10){ currentTime += ":0" + String(second()); }
    else { currentTime += ":" + String(second()); }
   
    Serial.print("2 seconds passed. Time is: ");
    Serial.println(currentTime);
 
}



void StrClear(char *str, char length)     // sets every element of str to 0 (clears array)
{
  for (int i = 0; i < length; i++) {
    str[i] = 0;
  }
}


char StrContains(char *str, char *sfind)    // searches for the string sfind in the string str - returns 1 if string found - returns 0 if string not found
{
  char found = 0;
  char index = 0;
  char len;

  len = strlen(str);

  if (strlen(sfind) > len) {
    return 0;
  }
  while (index < len) {
    if (str[index] == sfind[found]) {
      found++;
      if (strlen(sfind) == found) {
        return 1;
      }
    }
    else {
      found = 0;
    }
    index++;
  }

  return 0;
}


void WebRoleCalistir(void) 
{

x = 4;

}


void XMLGonder(EthernetClient cl)     
{

  cl.print("<?xml version = \"1.0\" ?>");
  cl.print("<inputs>");

  cl.print("<states>");
    cl.print("x");
  cl.println("</states>");

  cl.print("</inputs>");
}




Keep them out, with the F() macro.
client.println(F("Connection: keep-alive"));
Fixed.

while (webFile.available()) {
   client.write(webFile.read()); // send web page to client }
Sending a packet containing one character is incredibly inefficient. Use an array, and read and send at least 32 characters per packet.
I couldn't understand that..


Connect your ethernet shield to a wifi router and check out HMI droid (also available for iphone). You can control your entire home from your phone.
I tried Blynk. But I have to pay to create my whole Project. I didn't like the interface of HMI droid. Bu I'll give a chance after your suggestion. I may try to make my own app or get a Raspberry Pi fow Web server. I am confused.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Dec 03, 2016, 02:16 pm
Quote
I couldn't understand that..
Suppose you want to write a letter to your mother. You could write one word per page, fold the page up, put it in an envelope, address it, stamp it, and mail it.

Or, you could write several words per page.

Which would be more efficient? Which would be cheaper?

Code: [Select]
String currentTime = "";
Get rid of the stupid Strings. There is NO reason to piss away resources.

Code: [Select]
  Alarm.alarmRepeat(8,26,0, MorningAlarm);  // 8:30am every day
Bullshit.

Code: [Select]

//  currentMillis = millis();
//  if(currentMillis - previousMillis > interval) {
//    previousMillis = currentMillis;
//    timee();
//  }

When you are writing to your mother, one word per page, would you send her all the crossed out words?

Code: [Select]
          StrClear(HTTP_req, REQ_BUF_SZ);
You do not understand what NULL-terminated means, do you? If people blow through the stop sign at the end of the street, would putting up 12 stop signs make any difference?

Code: [Select]
void timee() {

    currentTime = "";
    if (day()<10){ currentTime += "0" + String(day()); }
      else { currentTime += String(day()); }
    if (month()<10){ currentTime += ".0" + String(month()); }
      else { currentTime += "." + String(month()); }
    currentTime += "." + String(year()) + " ";
    if (hour()<10){ currentTime += "0" + String(hour()); }
    else { currentTime += String(hour()); }
    if (minute()<10){ currentTime += ":0" + String(minute()); }
    else { currentTime += ":" + String(minute()); }
    if (second()<10){ currentTime += ":0" + String(second()); }
    else { currentTime += ":" + String(second()); }
   
    Serial.print("2 seconds passed. Time is: ");
    Serial.println(currentTime);
 
}

Why is this appropriate at 8:30?

Count how many useless calls to the String constructor and destructor you are causing here. Compare that to ONE call to sprintf().
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: karacayali on Dec 03, 2016, 09:04 pm
Why is this appropriate at 8:30?
timee function was just copy paste. I need alarms because I have to change the mod variable at specific times for heating control. For example every midnight the mod should change to sleep mode if mod type is automatic.
Code: [Select]

Alarm.alarmRepeat(23,45,0, alarm1);

void alarm1() {  //evernight 23:45:00
    if (modType==0){  //if automatic mode
        currentMod = 2; //1-Home 2-Sleep 3-Outside
      }
}



StrClear(HTTP_req, REQ_BUF_SZ);
You do not understand what NULL-terminated means, do you?
True I have no idea. I am not a programmer. Trying to learn. I couldn't learn much about this HTTP thing. Coppied from another project.

I removed all strings and comments. Still not working. The problem is not the strings in timestamp.

Code: [Select]


#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>
#include <Time.h>
#include <TimeLib.h>
#include <TimeAlarms.h>

#define REQ_BUF_SZ   60
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 200);
EthernetServer server(80);
File webFile;
char HTTP_req[REQ_BUF_SZ] = {0};
char req_index = 0;

int x;

void setup()
{

  setTime(8,25,53,8,1,2016);

  Alarm.alarmRepeat(8,26,0, MorningAlarm);
  Alarm.timerRepeat(2, Repeats);
  
  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);
  
  Serial.begin(9600);
  Serial.println("Initializing SD card...");
  if (!SD.begin(4)) {
    Serial.println("ERROR - SD card initialization failed!");
    return;
  }
  Serial.println("SUCCESS - SD card initialized.");
  if (!SD.exists("index.htm")) {
    Serial.println("ERROR - Can't find index.htm file!");
    return;
  }
  Serial.println("SUCCESS - Found index.htm file.");
  
  Ethernet.begin(mac, ip);
  server.begin();
}

void loop()
{
  
  EthernetClient client = server.available();
    
  if (client) {
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
         if (req_index < (REQ_BUF_SZ - 1)) {
          HTTP_req[req_index] = c;      
          req_index++;
        }
        if (c == '\n' && currentLineIsBlank) {
          client.println("HTTP/1.1 200 OK");  
          if (StrContains(HTTP_req, "ajax_inputs")) {
            client.println(F("Content-Type: text/xml"));
            client.println(F("Connection: keep-alive"));
            client.println();
            WebRoleCalistir();
            XMLGonder(client);
          }
          else {
            client.println(F("Content-Type: text/html"));
            client.println(F("Connection: keep-alive"));
            client.println();
            webFile = SD.open("index.htm");  
            if (webFile) {
              while (webFile.available()) {
                client.write(webFile.read());
              }
              webFile.close();
            }
          }
          
          Serial.print(HTTP_req);  
          req_index = 0;  
          StrClear(HTTP_req, REQ_BUF_SZ);
          break;
        }
        
        if (c == '\n') {        
          currentLineIsBlank = true;  
        }
        else if (c != '\r') {
          currentLineIsBlank = false;    
        }
        
      }
    }
    delay(1);    
    client.stop();
  }


}

void MorningAlarm() {
  Serial.println("Alarm: - MorningAlarm");
}

void Repeats() {
  Serial.println("Alarm: - Repeats");
}




void StrClear(char *str, char length)  
{
  for (int i = 0; i < length; i++) {
    str[i] = 0;
  }
}


char StrContains(char *str, char *sfind)
{
  char found = 0;
  char index = 0;
  char len;

  len = strlen(str);

  if (strlen(sfind) > len) {
    return 0;
  }
  while (index < len) {
    if (str[index] == sfind[found]) {
      found++;
      if (strlen(sfind) == found) {
        return 1;
      }
    }
    else {
      found = 0;
    }
    index++;
  }

  return 0;
}


void WebRoleCalistir(void)  
{

x = 4;

}


void XMLGonder(EthernetClient cl)    
{

  cl.print("<?xml version = \"1.0\" ?>");
  cl.print("<inputs>");

  cl.print("<states>");
    cl.print("x");
  cl.println("</states>");

  cl.print("</inputs>");
}




Result;

Initializing SD card...
SUCCESS - SD card initialized.
SUCCESS - Found index.htm file.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Dec 04, 2016, 11:15 am
Quote
The problem is not the strings in timestamp.
Well that narrows it down.

How is the Alarm class supposed to know that time has passed? You need to go back an re-read the documentation/examples for the Alarm class.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: odometer on Dec 04, 2016, 09:08 pm
True I have no idea. I am not a programmer. Trying to learn. I couldn't learn much about this HTTP thing. Coppied from another project.
If you copy things that you don't understand, and try to put them together without understanding how to put them together, that can lead to trouble. Now you are experiencing this kind of trouble.

Quote
I removed all strings and comments. Still not working. The problem is not the strings in timestamp.
It is good that you have done this. This is one way that programmers try to solve problems. They try to find out exactly what is causing the problem.


It seems that you have a big project in mind. Because it is such a big project, you should learn how to program, and not just copy and paste. Looking at examples is good, but you need to understand how they work, and how to modify them to suit your own needs. Also, know that some examples are poorly written, and not good to use.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Welsyntoffie on Dec 05, 2016, 02:42 am
If you setup your own Blynk server at your home then you dont need to pay anything.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: dgidney on Dec 10, 2016, 04:47 pm
Hi there,

I am super new to Arduino.

I am trying to use the time library to create a 60 second loop of on and off signals for an LED. Printing the second works perfect, getting 0-60 and then an overflow back to zero, but once I try to use second() in an if statement, the LED is always on. Am I using second() wrong?



#include <Time.h>
#include <TimeLib.h>



void setup() {
  // put your setup code here, to run once:
Serial.begin (9600);
  // set the digital pin as output:
  pinMode(LED_BUILTIN, OUTPUT);
   digitalWrite(LED_BUILTIN, LOW);


}

void loop() {
  // put your main code here, to run repeatedly:

if (second() == 5); {
 digitalWrite(LED_BUILTIN, HIGH);
}




Serial.println (second());
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Dec 10, 2016, 06:16 pm
Quote
once I try to use second() in an if statement, the LED is always on
Where do you turn the LED off in your code apart from in the setup() function ?

Check the syntax of the if command too.  Should the semicolon at the end be there I wonder ...
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Dec 10, 2016, 06:28 pm
Code: [Select]
if (second() == 5); {
Can you find a single other example where an if statement ends in a semi-colon?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Dec 10, 2016, 06:30 pm
Can you find a single other example where an if statement ends in a semi-colon?
Yes, I have seen plenty on here.  All of them wrong.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Dec 10, 2016, 06:34 pm
Yes, I have seen plenty on here.  All of them wrong.
OK. You got me there.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Pearo on Dec 20, 2016, 09:43 am
Hi folks, just find a very minor issue with Time when syncing with a GPS.

to recreate:
make a call to hour();
make a call to setTime();
make a call to adjustTime(timezoneCorrection);
make a call to hour();

occasionally hour() will return the time not adjusted for the timezone correction if the call is made within a second of calling adjustTime().

fix:
change refreshCache to force refresh
Code: [Select]


void refreshCache(time_t t, bool bForce = false) {
  if (t != cacheTime) {
    breakTime(t, tm);
    cacheTime = t;
  }
}


add new call to refreshCache to both setTime() and adjustTime()

Code: [Select]

void setTime(int hr,int min,int sec,int dy, int mnth, int yr){
 // year can be given as full four digit year or two digts (2010 or 10 for 2010); 
 //it is converted to years since 1970
  if( yr > 99)
      yr = yr - 1970;
  else
      yr += 30; 
  tm.Year = yr;
  tm.Month = mnth;
  tm.Day = dy;
  tm.Hour = hr;
  tm.Minute = min;
  tm.Second = sec;
  setTime(makeTime(tm));
 
  refreshCache(sysTime,true);
}

void adjustTime(long adjustment) {
  sysTime += adjustment;
 
  refreshCache(sysTime,true);
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: h35am on Jan 25, 2017, 08:37 am
Is there an easy way to time stamp.
I'm trying to put a time stamp next to my sensor reading but I don't know how to get this done.
Any help is greatly appreciated.

 
Code: [Select]
dateTijd = String(year() + "/" + month() +"/"+ day() +"-" + hour() +":" + minute() + ":" + second())
 message = String( paalID + ":" + temperatuurID + ":" + temperature*16 + ":" + temperature + ":" + dateTijd);
 Serial.println( message );
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Jan 25, 2017, 08:43 am
What does the snippet of code that you posted do ?  What do you want the output to look like ?  Where will it be output to ?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Jan 25, 2017, 12:10 pm
Quote
Is there an easy way to time stamp.
Yes. It does NOT involve pissing away resources using the String class.

sprintf() is more than you need, but it IS easy to use.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: h35am on Jan 25, 2017, 08:44 pm
Thank you all for the messages. I'm new to this and my code sends temperature data to lora network.
The format is so that it easily can be pulled from things network.
Therefore I need timestamp to send it with the rest of the data to the database.
Thanks again for all the help.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: theking2 on Mar 01, 2017, 04:35 pm
Hi the sample code contains an error:

Code: [Select]

TZ_adjust = 5.5; d = $(date + % s); t = $(echo "60*60*$TZ_adjust/1" | bc); echo T$(echo $d + $t | bc ) > / dev / ttyACM0
(: sourceend: )

Adjust the TZ_adjust value to your timezone and the serial port to your Arduino.

(: source lang = c getcode: )
#include <Time.h>

#define TIME_MSG_LEN 11 // time sync to PC is HEADER followed by Unix time_t as ten ASCII digits
#define TIME_HEADER 'T' // Header tag for serial time sync message
#define TIME_REQUEST 7 // ASCII bell character requests a time sync message

// T1262347200 //noon Jan 1 2010

void setup() {
 Serial.begin(9600);
}

void loop() {
 if (Serial.available() )
 {
 processSyncMessage();
 }
 if (timeStatus() == timeNotSet)
 Serial.println("waiting for sync message");
 else
 digitalClockDisplay();
 delay(1000);
}

void digitalClockDisplay() {
 // digital clock display of the time
 Serial.print(hour());
 printDigits(minute());
 printDigits(second());
 Serial.print(" ");
 Serial.print(day());
 Serial.print(" ");
 Serial.print(month());
 Serial.print(" ");
 Serial.print(year());
 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);
}

void processSyncMessage() {
 // if time sync available from serial port, update time and return true
 while (Serial.available() >= TIME_MSG_LEN ) { // time message consists of header & 10 ASCII digits
 char c = Serial.read() ;
 Serial.print(c);
 if ( c == TIME_HEADER ) {
 time_t pctime = 0;
 for (int i = 0; i < TIME_MSG_LEN - 1; i++) {
 c = Serial.read();
 if ( c >= '0' && c <= '9') {
 pctime = (10 * pctime) + (c - '0') ; // convert digits to a number
 }
 }
 setTime(pctime); // Sync Arduino clock to the time received on the serial port
 }
 }
}


generates this
Code: [Select]

Arduino: 1.8.1 (Windows Store 1.8.1.0) (Windows 10), Board: "Arduino/Genuino Uno"

sketch_mar01a:1: error: stray '$' in program

 TZ_adjust = 5.5; d = $(date + % s); t = $(echo "60*60*$TZ_adjust/1" | bc); echo T$(echo $d + $t | bc ) > / dev / ttyACM0

 ^

sketch_mar01a:1: error: stray '$' in program

sketch_mar01a:1: error: stray '$' in program

sketch_mar01a:1: error: stray '$' in program

sketch_mar01a:1: error: stray '$' in program

sketch_mar01a:1: error: 'TZ_adjust' does not name a type

sketch_mar01a:1: error: 'd' does not name a type

 TZ_adjust = 5.5; d = $(date + % s); t = $(echo "60*60*$TZ_adjust/1" | bc); echo T$(echo $d + $t | bc ) > / dev / ttyACM0

                  ^

sketch_mar01a:1: error: 't' does not name a type

 TZ_adjust = 5.5; d = $(date + % s); t = $(echo "60*60*$TZ_adjust/1" | bc); echo T$(echo $d + $t | bc ) > / dev / ttyACM0

                                     ^

sketch_mar01a:1: error: 'echo' does not name a type

 TZ_adjust = 5.5; d = $(date + % s); t = $(echo "60*60*$TZ_adjust/1" | bc); echo T$(echo $d + $t | bc ) > / dev / ttyACM0

                                                                            ^

C:\Users\J\Documents\Arduino\sketch_mar01a\sketch_mar01a.ino: In function 'void loop()':

sketch_mar01a:24: error: 'timeStatus' was not declared in this scope

  if (timeStatus() == timeNotSet)

                 ^

sketch_mar01a:24: error: 'timeNotSet' was not declared in this scope

  if (timeStatus() == timeNotSet)

                      ^

C:\Users\J\Documents\Arduino\sketch_mar01a\sketch_mar01a.ino: In function 'void digitalClockDisplay()':

sketch_mar01a:33: error: 'hour' was not declared in this scope

  Serial.print(hour());

                    ^

sketch_mar01a:34: error: 'minute' was not declared in this scope

  printDigits(minute());

                     ^

sketch_mar01a:35: error: 'second' was not declared in this scope

  printDigits(second());

                     ^

sketch_mar01a:37: error: 'day' was not declared in this scope

  Serial.print(day());

                   ^

sketch_mar01a:39: error: 'month' was not declared in this scope

  Serial.print(month());

                     ^

sketch_mar01a:41: error: 'year' was not declared in this scope

  Serial.print(year());

                    ^

C:\Users\J\Documents\Arduino\sketch_mar01a\sketch_mar01a.ino: In function 'void processSyncMessage()':

sketch_mar01a:59: error: 'time_t' was not declared in this scope

  time_t pctime = 0;

  ^

sketch_mar01a:63: error: 'pctime' was not declared in this scope

  pctime = (10 * pctime) + (c - '0') ; // convert digits to a number

  ^

sketch_mar01a:66: error: 'pctime' was not declared in this scope

  setTime(pctime); // Sync Arduino clock to the time received on the serial port

          ^

sketch_mar01a:66: error: 'setTime' was not declared in this scope

  setTime(pctime); // Sync Arduino clock to the time received on the serial port

                ^

exit status 1
stray '$' in program

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.


Could someone update the page? Also a link to the actual library would be helpful
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Mar 01, 2017, 06:02 pm
Which page are you referring to ?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cw8jwh on Mar 01, 2017, 07:27 pm
I'm using an Uno ( then built another one using a micro ) and a 128x64 LCD ( in SPI mode ) , the U8g2 and RTC libraries, a TinyRTC module and a DHT11 temp & humidity module.

Show date, time, temp and humidity.

Here's the sketch I pieced together:

Code: [Select]

// This sketch is for the Uno.

#include <Arduino.h>
#include <U8g2lib.h>
#include <Wire.h>
#include "RTClib.h"
RTC_DS1307 RTC;

#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif

/*
  U8glib Example Overview:
    Frame Buffer Examples: clearBuffer/sendBuffer. Fast, but may not work with all Arduino boards because of RAM consumption
    Page Buffer Examples: firstPage/nextPage. Less RAM usage, should work with all Arduino boards.
    U8x8 Text Only Example: No RAM usage, direct communication with display controller. No graphics, 8x8 Text only.
   
*/

// Please UNCOMMENT one of the contructor lines below
// U8g2 Contructor List (Frame Buffer)
// The complete list is available here: https://github.com/olikraus/u8g2/wiki/u8g2setupcpp
// Please update the pin numbers according to your setup. Use U8X8_PIN_NONE if the reset pin is not connected
U8G2_ST7920_128X64_F_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* CS=*/ 12, /* reset=*/ U8X8_PIN_NONE);


//KY015 DHT11 Temperature and humidity sensor
int DHpin = 8;
byte dat [5];
byte read_data () {
  byte data;
  for (int i = 0; i < 8; i ++) {
    if (digitalRead (DHpin) == LOW) {
      while (digitalRead (DHpin) == LOW); // wait for 50us
      delayMicroseconds (30); // determine the duration of the high level to determine the data is '0 'or '1'
      if (digitalRead (DHpin) == HIGH)
        data |= (1 << (7-i)); // high front and low in the post
      while (digitalRead (DHpin) == HIGH); // data '1 ', wait for the next one receiver
     }
  }
return data;
}
 
void start_test () {
  digitalWrite (DHpin, LOW); // bus down, send start signal
  delay (30); // delay greater than 18ms, so DHT11 start signal can be detected
 
  digitalWrite (DHpin, HIGH);
  delayMicroseconds (40); // Wait for DHT11 response
 
  pinMode (DHpin, INPUT);
  while (digitalRead (DHpin) == HIGH);
  delayMicroseconds (80); // DHT11 response, pulled the bus 80us
  if (digitalRead (DHpin) == LOW);
  delayMicroseconds (80); // DHT11 80us after the bus pulled to start sending data
 
  for (int i = 0; i < 4; i ++) // receive temperature and humidity data, the parity bit is not considered
    dat[i] = read_data ();
 
  pinMode (DHpin, OUTPUT);
  digitalWrite (DHpin, HIGH); // send data once after releasing the bus, wait for the host to open the next Start signal
}
 
void setup () {
  u8g2.begin();
  Serial.begin (9600);
  Wire.begin();
  RTC.begin();
  if (! RTC.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }
  pinMode (DHpin, OUTPUT);
}
 
void loop () {
  DateTime now = RTC.now();
  u8g2.clearBuffer();          // clear the internal memory
  u8g2.setFont(u8g2_font_amstrad_cpc_extended_8f);  // choose a suitable font
  start_test ();
  u8g2.setCursor(3,10);
  u8g2.print ("Date : ");
  u8g2.setCursor(55,10);
  u8g2.print(now.month(), DEC);
  u8g2.print('/');
  u8g2.print(now.day(), DEC);
  u8g2.print('/');
  u8g2.print(now.year(), DEC);
  u8g2.setCursor(3,19);
  u8g2.print ("Time : ");
  u8g2.setCursor(62,19);
  u8g2.print(now.hour(), DEC);
  u8g2.print(':');
  u8g2.print(now.minute(), DEC);
  u8g2.print(':');
  u8g2.print(now.second(), DEC);
  u8g2.setCursor (3, 37);
  u8g2.print ("Humidity :");
  u8g2.print (dat [0], DEC); // display the humidity-bit integer;
  u8g2.print ('.');
  u8g2.print (dat [1], DEC); // display the humidity decimal places;
  u8g2.println ('%');
  u8g2.setCursor(3,28);
  u8g2.print ("Temp :    ");
  u8g2.print (dat [2], DEC); // display the temperature of integer bits;
  u8g2.print ('.');
  u8g2.print (dat [3], DEC); // display the temperature of decimal places;
  u8g2.println ('C');
  u8g2.setFont(u8g2_font_profont22_tf);
  u8g2.drawStr(10,62,"VMFAT-101");
  u8g2.drawFrame(0, 0, 128, 64);
  u8g2.sendBuffer();          // transfer internal memory to the display
  delay (700);
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Redmor on Mar 18, 2017, 02:18 am
How can I directly contact the library developer?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cattledog on Mar 18, 2017, 06:00 am
Quote
How can I directly contact the library developer?
I don't know about the developer, but Time and Time Alarms are at the GitHub repository and show Paul Stoffregen as the owner with contact at http://www.pjrc.com/teensy/ (http://www.pjrc.com/teensy/)
and there is further contact info at https://www.pjrc.com/about/contact.html (https://www.pjrc.com/about/contact.html)
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: seanspotatobusiness on Mar 19, 2017, 03:36 pm
I'm a noob with a fairly short sketch. I can't actually program and am sort of figuring it out as I go by copying and pasting other people's code. I'm trying to make a silent alarm that just flashes a light at 2100 hrs every evening and carries on until I push a button but instead the LED starts to flash immediately after powering on and the button does not turn it off. I put in a serial monitor function to monitor the alarmState but it stays at zero until I physically touch the set-up at which point it starts giving random 1s. The state of the push button seems to make no difference. Thanks for any advice.

Code: [Select]
//This sketch triggers daily alarms at 2100 hrs.

#include <Time.h>
#include <TimeAlarms.h>

int buttonPin = 8;
int ledPin = 7;

int buttonState = 0;
int alarmState = 0;

// the setup function runs once when you press reset or power the board
void setup()
{
 setTime(19,59,59,0,0,0); // set time to 20:59:59
 // create the alarms
 Alarm.alarmRepeat(21,0,0, LithiumAlarm);  // 2100 hrs every day
  // initialize ledPin as an output and buttonPin as an input
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  Serial.begin(9600);      // open the serial port at 9600 bps:   
}

// functions to be called when an alarm triggers:
void LithiumAlarm(){
  alarmState = 1;
}
 
// the loop function runs over and over again forever
void loop() {
  if (alarmState=1) {
  digitalWrite(ledPin, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(ledPin, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
  if (digitalRead(buttonPin) == LOW) {
    alarmState = 0;
  }
}
Serial.print(alarmState);
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cattledog on Mar 19, 2017, 03:41 pm
Code: [Select]
if (alarmState=1)

Review the use of = and ==

= is assignment not comparison.  Alarm state is being set to the value of 1 not being compared to the value of one. It will always trigger the alarm routine.

Use
 if (alarmState==1)

Quote
I put in a serial monitor function to monitor the alarmState but it stays at zero until I physically touch the set-up at which point it starts giving random 1s. The state of the push button seems to make no difference. Thanks for any advice.
You may have button wiring issues as well. If changing to == doesn't solve your problem, ask a moderator to take this posting to the Programming section of the forum.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: seanspotatobusiness on Mar 19, 2017, 04:55 pm
Code: [Select]
if (alarmState=1)

Review the use of = and ==

= is assignment not comparison.  Alarm state is being set to the value of 1 not being compared to the value of one. It will always trigger the alarm routine.

Use
 if (alarmState==1)

You may have button wiring issues as well. If changing to == doesn't solve your problem, ask a moderator to take this posting to the Programming section of the forum.
Thanks very much. Unfortunately now the alarmState stays 0 when I expect it to actiivate! I'll take it to the programming section.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cattledog on Mar 19, 2017, 05:06 pm
I missed it when I first looked at your post, but time alarms requires the use of  Alarm.delay();  to function.

See the documentation. Replace all calls to delay() with calls to Alarm.delay(). If there is no use of delay() in the code, add Alarm.delay() to the top of loop().
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: BlitzSSS on Mar 26, 2017, 03:06 am
Hi All

Using the TimeNTP_ESP8266 WiFi example, how do I set the timezone for a zone which has a half hour increment i.e UTC+9:30?

I've tried setting the const int timeZone variable at the start to many different permutations with a half hour increment.
I've also tried using adjustTime(1800) but can't seem to find the right spot to get this working.
Lastly tried altering the line "return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR".

yes I'm a noob if the answer is obvious please be gently and point it out to me but I have tried to solve this on my own before turning to this forum for help :)

Thanks
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: jarandacu on Apr 13, 2017, 05:53 pm
Hi !

I want to set the time just once in the arduino and then just execute the alarm program, how i can do that ?? i tried:

    1. comment the set time:
    //setTime(9,30,00,17,3,17);
    But does not work, the time reset to 0:0:0.

    2. No argument
    setTime();
    it cant be compiled.

Im using the example code:


#include <Time.h>
#include <TimeAlarms.h>

void setup()
{
  Serial.begin(9600);
  setTime(8,29,0,1,1,11); // set time to Saturday 8:29:00am Jan 1 2011
  // 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);
}

Thanks !

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Apr 13, 2017, 06:09 pm
What time do you want to set the program to ?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: maskrtnik01 on May 01, 2017, 06:16 pm
Hello,

I am using a NodeMCU board with Arduino IDE.
When I upload TimerAlarmExample sketch to my NodeMCU, it is working well.

Then I have added alarm functions to another example(for getting time from NTP servers). Time is working, I get NTP time successfully, but alarms/timers are simply dead.
Here is my code.

Code: [Select]


/*
 * Time_NTP.pde
 * Example showing time sync to NTP time source
 *
 * This sketch uses the ESP8266WiFi library
 */
 
#include <TimeLib.h>
#include <TimeAlarms.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

const char ssid[] = "**********";  //  your network SSID (name)
const char pass[] = "**********";       // your network password

// NTP Servers:
IPAddress timeServer(132, 163, 4, 101); // time-a.timefreq.bldrdoc.gov
// IPAddress timeServer(132, 163, 4, 102); // time-b.timefreq.bldrdoc.gov
// IPAddress timeServer(132, 163, 4, 103); // time-c.timefreq.bldrdoc.gov


const int timeZone = 1;     // Central European Time
//const int timeZone = -5;  // Eastern Standard Time (USA)
//const int timeZone = -4;  // Eastern Daylight Time (USA)
//const int timeZone = -8;  // Pacific Standard Time (USA)
//const int timeZone = -7;  // Pacific Daylight Time (USA)


WiFiUDP Udp;
unsigned int localPort = 8888;  // local port to listen for UDP packets


void RepeatedAlarm()
{
  Serial.println("Alarm.");
}
void RepeatedTimer()
{
  Serial.println("Timer.");
}

void setup()
{
  Serial.begin(9600);
  while (!Serial) ; // Needed for Leonardo only
  delay(250);
  Serial.println("TimeNTP Example");
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, pass);
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  
  Serial.print("IP number assigned by DHCP is ");
  Serial.println(WiFi.localIP());
  Serial.println("Starting UDP");
  Udp.begin(localPort);
  Serial.print("Local port: ");
  Serial.println(Udp.localPort());
  Serial.println("waiting for sync");
  setSyncProvider(getNtpTime);
  Alarm.alarmRepeat(16,57,0,RepeatedAlarm);
  Alarm.timerRepeat(10,RepeatedTimer);
}

time_t prevDisplay = 0; // when the digital clock was displayed

void loop()
{  
  if (timeStatus() != timeNotSet) {
    if (now() != prevDisplay) { //update the display only if time has changed
      prevDisplay = now();
      digitalClockDisplay();  
    }
  }
}

void digitalClockDisplay(){
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print(" ");
  Serial.print(day());
  Serial.print(".");
  Serial.print(month());
  Serial.print(".");
  Serial.print(year());
  Serial.println();
}



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



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

const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets

time_t getNtpTime()
{
  while (Udp.parsePacket() > 0) ; // discard any previously received packets
  Serial.println("Transmit NTP Request");
  sendNTPpacket(timeServer);
  uint32_t beginWait = millis();
  while (millis() - beginWait < 1500) {
    int size = Udp.parsePacket();
    if (size >= NTP_PACKET_SIZE) {
      Serial.println("Receive NTP Response");
      Udp.read(packetBuffer, NTP_PACKET_SIZE);  // read packet into the buffer
      unsigned long secsSince1900;
      // convert four bytes starting at location 40 to a long integer
      secsSince1900 =  (unsigned long)packetBuffer[40] << 24;
      secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
      secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
      secsSince1900 |= (unsigned long)packetBuffer[43];
      return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
    }
  }
  Serial.println("No NTP Response :-(");
  return 0; // return 0 if unable to get the time
}

// send an NTP request to the time server at the given address
void 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();
}


Does anyone see any problem with this sketch? Or any other reason, why it is not working?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cattledog on May 01, 2017, 11:00 pm
Quote
Does anyone see any problem with this sketch?
Time Alarms require the use of Alarm.delay(). https://github.com/PaulStoffregen/TimeAlarms (https://github.com/PaulStoffregen/TimeAlarms)

Quote
Your sketch should call the Alarm.delay() function instead of the Arduino delay() function when
using the Alarms library.  The timeliness of triggers depends on sketch delays using this function.
Alarm.delay( period); // Similar to Arduino delay - pauses the program for the period (in milliseconds).
Q: Why must I use Alarm.delay() instead of delay()?
A: Task scheduling is handled in the Alarm.delay function.
Tasks are monitored and  triggered from within the Alarm.delay call so Alarm.delay should be called
whenever a delay is required in your sketch.
If your sketch waits on an external event (for example,  a sensor change),
make sure you repeatedly call Alarm.delay while checking the sensor.
You can call Alarm.delay(0) if you need to service the scheduler without a delay.
If there are no delays in loop, you can call Alarm.delay(0);
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: maskrtnik01 on May 02, 2017, 11:28 am
Thank you.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Goet on Jul 19, 2017, 11:14 pm
I'm using Time and TimeAlarm Paul Stoffregen libs. Its readme points to this thread, so here I am.
I'm coding an alarm clock and I'd need to set some events on annual base.
I'm not entirely sure if what I'm doing is correct.
Here's what I'm doing, basically;
Code: [Select]

#include <LiquidCrystal_I2C.h>
#include <Wire.h>
#include <Time.h> // https://github.com/PaulStoffregen/Time
#include <TimeAlarms.h> // https://github.com/PaulStoffregen/TimeAlarms

#define LCDWIDTH 20
#define LCDHEIGHT 4

LiquidCrystal_I2C lcd(0x27, LCDWIDTH, LCDHEIGHT);

static char info[15]; // used for outputting date & time
static char tmp[5]; // idem

void setup() {
  // lcd init
  lcd.begin(LCDWIDTH, LCDHEIGHT);
  lcd.init();
  lcd.clear();
  lcd.backlight();

  // setting a next-to-event date & time
  setTime(23, 59, 55, 31, 12, 2017);

  // setting a test event: New Year's Eve
  time_t testTime;
  TimeElements tt;
  tt.Second = 0;
  tt.Minute = 0;
  tt.Hour = 0;
  tt.Day = 1;
  tt.Month = 1;
  tt.Year = 2018 - 1970;
  testTime = makeTime(tt);
  Alarm.triggerOnce(testTime, testEvent);

}

void loop() {
  getDate();
  lcd.setCursor(alignCenter(strlen(info)), LCDHEIGHT / 2 - 1);
  lcd.print(info);
  getTime();
  lcd.setCursor(alignCenter(strlen(info)), LCDHEIGHT / 2);
  lcd.print(info);
  Alarm.delay(1000);
  lcd.clear();
}

void testEvent() {
  // for events happening before 28 feb
  if ((year() % 4 == 0 && year() % 100 != 0) || year() % 400 == 0) {
    // leap year --> non leap year : 31622400 seconds (366 days)
    Alarm.timerOnce(31622400, testEvent);
  } else {
    Alarm.timerOnce(31536000, testEvent);
  }
  lcd.clear();
  lcd.print("HAPPY NEW YEAR");
  Alarm.delay(2000);
}

void getDate() {
  strcpy(info, dayShortStr(weekday()));
  info[3] = ' ';
  info[4] = 0;
  useTmp(day());
  strcat(info, tmp);
  byte len = strlen(info);
  info[len] = '/';
  info[len + 1] = 0;
  useTmp(month());
  strcat(info, tmp);
  len = strlen(info);
  info[len] = '/';
  info[len + 1] = 0;
  useTmp(year());
  strcat(info, tmp);
}

void getTime() {
  useTmp(hour());
  strcpy(info, tmp);
  byte len = strlen(info);
  info[len] = ':';
  info[len + 1] = 0;
  useTmp(minute());
  strcat(info, tmp);
  len = strlen(info);
  info[len] = ':';
  info[len + 1] = 0;
  useTmp(second());
  strcat(info, tmp);
}

void useTmp(int x) {
  if (x == 0) {
    tmp[0] = '0';
    tmp[1] = 0;
    return;
  }
  byte n = log10(x) + 1;
  if (n == 1) {
    tmp[0] = x + '0';
    tmp[1] = 0;
    return;
  }
  if (n == 2) {
    tmp[2] = 0;
    tmp[1] = (x % 10) + '0';
    tmp[0] = ((x / 10) % 10) + '0';
    return;
  }
  while (n > 0) {
    tmp[--n] = (x % 10) + '0';
    x /= 10;
  }
  tmp[4] = 0;
}

int alignCenter(int l) {
  return l % 2 == 0 ? LCDWIDTH / 2 - (l / 2) : LCDWIDTH / 2 - (l / 2) - 1;
}


Triggered event, in this example, is New Year's Eve. I set it as 0 hour 0 minute 0 seconds of 1/1/2018, so it's happening before 28 Feb. The reason I'm not using Alarm.timerRepeat(seconds, methodName) in setup method is exactly this: I have to consider leap years to find the exact amount of seconds to set.

If the event happens BEFORE 28 Feb
     from non leap year to leap year or from non leap year to non leap year, we need to "wait" 31536000 seconds (365 days)
     from leap year to non leap year, we need to "wait" 31622400 seconds (366 days)

So I'm using the "mechanism" to call Alarm.triggeredOnce in the setup method, and then Alarm.timerOnce in my testEvent method, where I'm able to set the correct amount of seconds depending on the situation.

In this way I should be able to schedule events on annual base.

I've already tested the whole mechanism with small amount of time setted in testEvent method:
Code: [Select]

  } else {
    Alarm.timerOnce(10, testEvent);
  }

and it's working: every ten seconds I get the event message.

First question: is the thinking right? Is this the correct way to trigger an event on annual base?

Second question: for displaying date & time every second on lcd I'm using two global static char arrays and some method (getDate, getTime and useTmp) to fill them. There's a better way to do it, or can my "system" be optimized?

Thanks for any help : )
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cattledog on Jul 20, 2017, 12:56 am
Quote
I'm coding an alarm clock and I'd need to set some events on annual base.
The time library knows about leap years so you don't need to work it out by yourself and then switch to alarm.timerOnce.

I think you can just reconfigure  alarm.triggerOnce() with a new value from makeTime() and set it in the testEvent() handler.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Goet on Jul 20, 2017, 02:08 am
I think you can just reconfigure  alarm.triggerOnce() with a new value from makeTime() and set it in the testEvent() handler.
Man you're right, just tested it. I can declare time_t testTime and TimeElements tt globally, set them once in setup method and go like this:
Code: [Select]
void testEvent() {
  tt.Year = year() + 1 - 1970;
  testTime = makeTime(tt);
  Alarm.triggerOnce(testTime, testEvent);

  lcd.clear();
  lcd.print("HAPPY NEW YEAR");
  Alarm.delay(2000);
}

and forget about the rest, great!
Thank you cattledog, very much appreciated : )

What about the second question (anyone)? Any advices?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: y-master on Aug 02, 2017, 05:01 pm
Hi everyone,

I just started to play with arduino and I have my first issue with Time and TimeAlarms.
My alarm works when I set the time manually but when I get the time from a DS1307 chip it never run.

Code who work (I removed the functions) :
Code: [Select]


#include <Time.h>
#include <TimeAlarms.h>

// variables
#define RELAY1 2

void setup() {
  Serial.begin(9600);
  pinMode(RELAY1, OUTPUT);
  setTime(00,00,00,27,07,2017);
  Alarm.alarmRepeat(00,01,0,StartPump01);
  digitalWrite(RELAY1,LOW);
}

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

}


Code who don't work :
Code: [Select]

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

// variables
#define RELAY1 2
#define RELAY2 3

void setup() {
  Serial.begin(9600);
  pinMode(RELAY1, OUTPUT);
  Alarm.alarmRepeat(23,15,0,StartPump01);
  digitalWrite(RELAY1,LOW);

  // the function to get 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");
}

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


Any idea ?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: aarg on Aug 02, 2017, 05:03 pm
Have you tested the RTC separately from the Time library?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: y-master on Aug 02, 2017, 05:08 pm
Yes, it's been initialised correctly and digitalClockDisplay(); return the correct time and date
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cattledog on Aug 02, 2017, 06:53 pm
Quote
Yes, it's been initialised correctly and digitalClockDisplay(); return the correct time and date
Do you see "RTC has set the system time" ?

Code: [Select]
Alarm.alarmRepeat(23,15,0,StartPump01);

Is the RTC in 24 hour mode?




Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: y-master on Aug 02, 2017, 07:05 pm
I've added some debug info to the setup :
Code: [Select]

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(RELAY1, OUTPUT);
  Alarm.alarmRepeat(17,02,0,StartPump01);
  digitalWrite(RELAY1,LOW);

  // the function to get the time from the RTC
  setSyncProvider(RTC.get);
  Serial.print("Time Status : ");
  Serial.print(timeStatus());
  Serial.println();
 
  if(timeStatus()!= timeSet)
     Serial.println("Unable to sync with the RTC");
  else
     Serial.println("RTC has set the system time");         
 
  Serial.print("value from rtc chip : ");
  Serial.print(RTC.get());
  Serial.println();
  Serial.print("value from system time : ");
  Serial.print(now());
  Serial.println();
  Serial.print("Time library output : ");
  digitalClockDisplay();
  Serial.println();
}


And this is what I get on console :
Time Status : 2
RTC has set the system time
value from rtc chip : 1501693287
value from system time : 1501693287
Time library output : 17:01:27 2/8/2017


Is the RTC in 24 hour mode?
How can I check this ?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cattledog on Aug 02, 2017, 07:16 pm
try adding a simple alarm function

Code: [Select]
void StartPump01()
{
Serial.println("StartPump01 alarm triggered");
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: y-master on Aug 02, 2017, 07:32 pm
My function is already quite simple :
Code: [Select]
void StartPump01(){
  Serial.println("Alarm: Start the pump 01");
  digitalWrite(RELAY1,HIGH);          // Turns ON Relay
  Serial.println("RELAY1 : HIGH");
  Alarm.delay(20000); // wait 20 seconds
  digitalWrite(RELAY1,LOW);           // Turns OFF Relay
  Serial.println("RELAY1 : LOW");
}


I've just read this https://www.arduino.cc/en/Tutorial/Memory about small sram size on uno.
Could it be a memory issue ?
Do I need to remove all my debug output from sketch ?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: aarg on Aug 02, 2017, 07:35 pm
Have you tried running it with your relay disconnected? It might be resetting the board.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: y-master on Aug 02, 2017, 07:42 pm
Have you tried running it with your relay disconnected? It might be resetting the board.
Thanks for the advice but if you check my first message, I said that the same code is working if I set the time manually and not with RTC library.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cattledog on Aug 02, 2017, 08:09 pm
When you run  the basic read sketch in the ds1307 library with the rtc alone do you see the time advance?
Code: [Select]
#include <Wire.h>
#include <Time.h>
#include <DS1307RTC.h>

void setup() {
  Serial.begin(9600);
  while (!Serial) ; // wait for serial
  delay(200);
  Serial.println("DS1307RTC Read Test");
  Serial.println("-------------------");
}

void loop() {
  tmElements_t tm;

  if (RTC.read(tm)) {
    Serial.print("Ok, Time = ");
    print2digits(tm.Hour);
    Serial.write(':');
    print2digits(tm.Minute);
    Serial.write(':');
    print2digits(tm.Second);
    Serial.print(", Date (D/M/Y) = ");
    Serial.print(tm.Day);
    Serial.write('/');
    Serial.print(tm.Month);
    Serial.write('/');
    Serial.print(tmYearToCalendar(tm.Year));
    Serial.println();
  } else {
    if (RTC.chipPresent()) {
      Serial.println("The DS1307 is stopped.  Please run the SetTime");
      Serial.println("example to initialize the time and begin running.");
      Serial.println();
    } else {
      Serial.println("DS1307 read error!  Please check the circuitry.");
      Serial.println();
    }
    delay(9000);
  }
  delay(1000);
}

void print2digits(int number) {
  if (number >= 0 && number < 10) {
    Serial.write('0');
  }
  Serial.print(number);
}


When you run the time library with setSynchProvider(RTC.get), the time library updates its time from the rtc every 5 minutes. When you run your alarm code for more than 5 minutes does the time advance and not go back in time every 5 minutes?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: y-master on Aug 02, 2017, 08:21 pm
Some news : I've modified my first sketch (the one without RTC) to add the RTC sync and IT WORKS !
Now I will compare the two codes to find where is the f...

Thanks a lot for the help


For reference, this is working with :
Code: [Select]

#include <Time.h>
#include <TimeAlarms.h>
#include <DS1307RTC.h>

// variables
#define RELAY1 2

void setup() {
  Serial.begin(9600);
  pinMode(RELAY1, OUTPUT);
  setTime(17,30,00,27,07,2017);
  setSyncProvider(RTC.get);
  Alarm.alarmRepeat(17,59,0,StartPump01);
  digitalWrite(RELAY1,LOW);
}

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

}

void StartPump01(){
  Serial.println("Alarm: Start the pump 01");
  digitalWrite(RELAY1,HIGH);          // Turns ON Relay
  Serial.println("RELAY1 : HIGH");
  Alarm.delay(20000); // wait 20 seconds
  digitalWrite(RELAY1,LOW);           // Turns OFF Relays 1
  Serial.println("RELAY1 : LOW");
}
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Carlcox89 on Aug 24, 2017, 02:48 pm
Some news : I've modified my first sketch (the one without RTC) to add the RTC sync and IT WORKS !
Now I will compare the two codes to find where is the f...

Thanks a lot for the help


For reference, this is working with :
Code: [Select]

#include <Time.h>
#include <TimeAlarms.h>
#include <DS1307RTC.h>

// variables
#define RELAY1 2

void setup() {
  Serial.begin(9600);
  pinMode(RELAY1, OUTPUT);
  setTime(17,30,00,27,07,2017);
  setSyncProvider(RTC.get);
  Alarm.alarmRepeat(17,59,0,StartPump01);
  digitalWrite(RELAY1,LOW);
}

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

}

void StartPump01(){
  Serial.println("Alarm: Start the pump 01");
  digitalWrite(RELAY1,HIGH);          // Turns ON Relay
  Serial.println("RELAY1 : HIGH");
  Alarm.delay(20000); // wait 20 seconds
  digitalWrite(RELAY1,LOW);           // Turns OFF Relays 1
  Serial.println("RELAY1 : LOW");
}

I think that all you were missing was the call to setTime()
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: wgatlin on Oct 18, 2017, 12:15 am
Hello Forum Users,

I'm a novice Arduino user and I have found myself stuck.  I am trying to get my device to respond to an alarm at a predetermined time, but there doesn't seem to be any response from the serial monitor or hardware when the time comes.  I believe my code is properly commented so hopefully it should be pretty simple to follow my breadcrumbs.  I would certainly appreciate any input!

Code: [Select]
//Catomatic: An automated cat food and water station
//A hair-brained project by Wayne Gatlin
//last edit 14May2017

/*
Description of the project:
The purpose of this project is to control the timing of two outputs that are used to
dispense food and water to Murf.  One output is a low-torque electric motor (12v)
that turns a worm drive to dispense food and the other is a soleniod (12v) that
dispenses water.  An Arduino Uno with a RTC controls the timing of food and water cycles.   
Each output is activated by a seperate TIP120 transistor that receives a 5v signal from the   
Arduino that opens the defined output to the 12v current. 

Description of the circuit:
*A DC 12v 1.5A power supply, with the ground wire connected to 12v breaboard ground and the power
   connected to the 12v breadboard power
*A DC motor connected to 12v power and a TIP120 tranistor
*A DC solenoid valve connected to 12v power and a TIP120 tranistor
*Feedmotor TIP120 tranistor, with the Base connected to digital pin 3, the Emitter to 12v ground,
 and the Collector to one lead from a 12v DC motor
*watersolenoid TIP120 tranistor, with the Base connected to digital pin 4, the Emitter to ground,
 and the Collector to one lead from a 12v DC solenoid valve
*manual feed Pushbotton that completes 12v circuit from motor to ground, bypassing transistor control
*manual water Pushbotton that completes 12v circuit from solenoid to ground, bypassing transistor control
*RTC to control timing of events

The objective of this code is to:
1. Use the arduino's outputs to send 5v signals to the transistors for the motor and solenoid
so that they turn on at the defined times and are open for the correct amount of time
2. Define a set amount of time that each output is open (longer=more food or water dispensed)
3. Create a timed daily cycle of three food and water events (breakfast, lunch, dinner)
4. Ideally allow the Arduino to "sleep" until it is interruped for the next event 
*/

//Step 1: Call libraries
#include <Wire.h>       //This library allows the Uno to communicate with I2C / TWI devices. On the Arduino boards with the R3 layout (1.0 pinout), the SDA (data line) and SCL (clock line) are on the pin headers close to the AREF pin.
#include "RTClib.h"     //I beleive this library allows the RTC to communicate with the Arduino
#include <TimeLib.h>    //This header file contains definitions of functions to get and manipulate date and time information.
#include <TimeAlarms.h> //I believe this libarry allows me to schedule time-based tasks

RTC_DS1307 RTC;         //I'm not sure what this function does, maybe defines the type of RTC?  It was here in the example

//Step 2: Define the variables
    //I beleive int indicates that these are the digital output pins that will be used to communicate with hardware.  Greg says they should be const int because the variables don't change?
   
int feedmotor = 3;      //The motor for food will be controlled by digial output pin 3
int watersolenoid = 4;  //The solenoid for water will be controlled by digial output pin 4
    //Do I need an additional one for the RTC?

/**************************
 
     SETUP FUNCTION
 
***************************/

// Step 3: Run the setup
    //The setup() function is called when a sketch starts. Use it to initialize variables, pin modes, start using libraries, etc.
    //The setup function will only run once, after each powerup or reset of the Arduino board.

void setup()
{
//establish communication with computer
    Serial.begin(9600); //My understanding is that this sets the communiaction rate with the computer(?) and is necessary for all sketches

//Call the libraries that were included in Step 1
    Wire.begin();       //Starts the wire library
    RTC.begin();        //Starts the RTC library
 
    //I don't think I need time.begin() (Not in example code or search results)but I don't know why
    //Similarily, I dont think I need TimeAlarms.begin()

//Tell the arduino what I've called the outputs
    pinMode(feedmotor, OUTPUT);      //Defines that the feedmotor (pin 3 from step 2) is an output device
    pinMode(watersolenoid, OUTPUT);  //Defines that the watersolenoid (pin 4 from step 2) is an output device
    pinMode(LED_BUILTIN, OUTPUT);   //defines onboard LED

//Test to make sure the RTC is running properly
  if (! RTC.isrunning())
    {
    Serial.println("RTC is NOT running!");
    }


/**************************
 
           LOOPS
 
***************************/

//Step 4: Describe the loop

void loop() { //curly bracket that defines start of the loop

//this sets the RTC clock to current time and date in the serial monitor
//Does this require an LCD?  I would like to add one in the future.
    DateTime now = RTC.now();         //this calls current time and date from RTC
   
    Serial.print(now.hour(), DEC);    //this set of functions prints the time every second in the serial monitor
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

//Define the times that food and water will be delivered
//I don't know if these are defined correctly, from example code
    Alarm.alarmRepeat(07,00,0, Breakfast);    // An alarm called Breakfast happens at 7:00am every day
    Alarm.alarmRepeat(12,00,00, Lunch);        // An alarm called Lunch happens at 12:00pm every day
    Alarm.alarmRepeat(19,00,0, Dinner);       // An alarm called Dinner happens at7:00pm every day

//I think this is needed?
Alarm.delay(1000); // wait one second between clock display
}


//Create a loop that defines a feeding
void FeederON() {                         //I think this is just a title for this particular function
    digitalWrite(feedmotor, HIGH);        //Turns the feedmotor on
    Serial.println("Feeding the Beast");  //text on the future LCD
    //future project: LED indicator light
    //future project: LCD scrolling message
    //future project: sound bite to announce feeding
    delay(5000);                           //This is the amount of time the motor will turn dispensing food
    Serial.println("Feeding Complete");   //Text on the future LCD
}

//Create a loop that defines a watering
void WatererON() {                        //I think this is just a title for this particular function
    digitalWrite(watersolenoid, HIGH);    //Turns the watersolenoid on
    Serial.println("Hydrating");          //text on the future LCD
    //future project: LED indicator light
    //future project: LCD scrolling message
    //future project: sound bite to announce watering
    delay(5000);                           //This is the amount of time the motor will turn dispensing food
    Serial.println("Hydration Complete"); //Text on the future LCD
}

//Define what will happen at each of the three scheduled meal times
void Breakfast() {
  Serial.println("test run"); 
    //FeederON();   
    //WatererON();
}

void Lunch() {
    FeederON();
    WatererON();
}

void Dinner() {
    FeederON();
    WatererON();
}


Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Oct 18, 2017, 12:21 am
Please post your code here
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: rtek1000 on Oct 18, 2017, 04:01 pm
Hello,

I do not really believe that an arduino (or other microcontroller) works well for so long without the need for maintenance or replacement.

But the Time library only works until the year 2105.

And we already have RTC models with compensation until the year 2399.

Can you make a repair to accept up to 2399, please?


Examples:
http://www.microchip.com/wwwproducts/en/MCP7940N
http://www.microchip.com/wwwproducts/en/MCP79410

--->    Leap year compensated  to 2399 <---
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Oct 18, 2017, 04:17 pm
Quote
But the Time library only works until the year 2105.
Specifically, what will stop working 88 years from now?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: odometer on Oct 18, 2017, 04:41 pm
Specifically, what will stop working 88 years from now?
That's when the angels will have worn out their pinhead and will need a new dance floor.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Oct 18, 2017, 04:50 pm
Quote
But the Time library only works until the year 2105.
I understand that the fix will be made available in 2104.  Please check the thread again then.   :)
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: rtek1000 on Oct 23, 2017, 01:48 am
Hello,

Well, not to mention the jokes,

I think it's a very good transformation, because the year-end timestamp of 2399 is a 34-bit number: 13569465599 (DEC) or 11 00101000 11001101 10011100 11111111 (BIN) or 3 28 CD 9C FF (HEX):

Epoch timestamp: 13569465599
Timestamp in milliseconds: 13569465599000
Human time (GMT): Friday, 31 de December de 2399 às 23:59:59

https://www.epochconverter.com/

Quote
How to know if it is a Leap Year:
[Yes] Leap Years are any year that can be evenly divided by 4 (such as 2012, 2016, etc)
[Not] except if it can be evenly divided by 100, then it isn't (such as 2100, 2200, etc)
[Yes] except if it can be evenly divided by 400, then it is (such as 2000, 2400)
https://www.mathsisfun.com/leap-years.html

The year variables of the current Time library are converted to two digits, so they will also need reform.

Quote
TimeLib.h:

typedef struct  {
  uint8_t Second;
  uint8_t Minute;
  uint8_t Hour;
  uint8_t Wday;   // day of week, sunday is day 1
  uint8_t Day;
  uint8_t Month;
  uint8_t Year;   // offset from 1970;
} tmElements_t, TimeElements, *tmElementsPtr_t;
I know it sounds like bullshit to review it today, but when you blink your eyes, you'll notice that many years have passed.

Thank you!
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: rtek1000 on Oct 23, 2017, 07:12 am
Hi,

I changed some variables (for test) and now I can run the code until the year 32456  :o
(for time display time 0xdfffffffff I do not believe mankind will still use an Arduino at this time, but who will know this?  :P )

Tested with sketch TimeSerial64.zip, Use of resources:

With modifications:
Sketch uses 6102 bytes (18%) of program storage space. Maximum is 32256 bytes.
Global variables use 252 bytes (12%) of dynamic memory, leaving 1796 bytes for local variables. Maximum is 2048 bytes.

Without modifications:
Sketch uses 5350 bytes (16%) of program storage space. Maximum is 32256 bytes.
Global variables use 235 bytes (11%) of dynamic memory, leaving 1813 bytes for local variables. Maximum is 2048 bytes.


(Note: I do not know where I read, but there is some more time correction to be performed for many years, I do not know if the code makes up for all these deviations  :( )

Note: In order to print the 64-bit number on the serial port, an adaptation is required  >:( .
(More info: https://forum.arduino.cc/index.php?topic=58697.0)

I randomly tested some dates, and I noticed that the day of the week is correct with the site below, until the year 9999, because the site only allows 4 digits for the year  :) :
https://www.epochconverter.com/

Added number 32456 in file names for test reference only

Thank you!
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Oct 23, 2017, 01:19 pm
There really is a much simpler (and therefore smaller) fix. The key is that the epoch value holds the number of seconds since 1970. Add one more field to the struct to hold the reference year. It should default to 1970. But, it does NOT have to be 1970.It could be 2000. Or 2070. As long as any instance of time knows that it is the number of seconds since some KNOWN point in time, relative times are easy to deal with.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: rtek1000 on Oct 23, 2017, 02:51 pm
There really is a much simpler (and therefore smaller) fix. The key is that the epoch value holds the number of seconds since 1970. Add one more field to the struct to hold the reference year. It should default to 1970. But, it does NOT have to be 1970.It could be 2000. Or 2070. As long as any instance of time knows that it is the number of seconds since some KNOWN point in time, relative times are easy to deal with.
Good point!

I found a document about a rtc that takes time by century, but a microchip rtc (up to 2399) runs between 2001 and 2399 (to skip the leap year of 400 years)

Page 12:
http://www.microcrystal.com/images/_Product-Documentation/02_Oscillator_&_RTC_Modules/02_Application_Manual/RV-4162-C7_App-Manual.pdf

Page 15:
http://ww1.microchip.com/downloads/en/DeviceDoc/20005010F.pdf
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: BlitzSSS on Oct 24, 2017, 08:00 am
Hi All

Using the TimeNTP_ESP8266 WiFi example, how do I set the timezone for a zone which has a half hour increment i.e UTC+9:30?

I've tried setting the const int timeZone variable at the start to many different permutations with a half hour increment.
I've also tried using adjustTime(1800) but can't seem to find the right spot to get this working.
Lastly tried altering the line "return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR".

yes I'm a noob if the answer is obvious please be gently and point it out to me but I have tried to solve this on my own before turning to this forum for help :)

Thanks
Hi All

Don't think I got a reply to this, can anyone help me set a timezone with a half hour increment i.e UTC+9:30?
?

Thanks
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: odometer on Nov 11, 2017, 10:25 pm
Hi All

Using the TimeNTP_ESP8266 WiFi example, how do I set the timezone for a zone which has a half hour increment i.e UTC+9:30?

I've tried setting the const int timeZone variable at the start to many different permutations with a half hour increment.
I've also tried using adjustTime(1800) but can't seem to find the right spot to get this working.
Lastly tried altering the line "return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR".

yes I'm a noob if the answer is obvious please be gently and point it out to me but I have tried to solve this on my own before turning to this forum for help :)

Thanks
Which sketch exactly are you trying to modify?
Can you post a link to the sketch, and/or post the code itself?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: aarg on Nov 11, 2017, 10:30 pm
Is timeZone an integer? You might have to change that to accommodate minutes instead of hours, or hard code it with something like:
Code: [Select]
return secsSince1900 - 2208988800UL + SECS_PER_HOUR * 3 / 2;
... (an hour and a half = 1.5 = 3/2 hours)
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: Ahank on Dec 16, 2017, 10:12 pm
Is there a way to change the frequency[seconds] of a repeat alarm while running ?

Alarm.timerRepeat(seconds, function); 

Regards
Ahank
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Dec 16, 2017, 11:19 pm
From the TimeAlarms readme
Quote
write(ID,  value);  -  write the value (and enable) the alarm for the given ID 
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: tochinet on Jan 14, 2018, 07:31 pm
Joining the thread. I was a bit surprised to see that including the  TimeAlarms.h library in my sketch directly adds more than 2000 bytes in the compiled program (but only 70 bytes of RAM) while my use of it is quite limited : I replace two delays by Alarm.delay and I create one alarm that fires at midnight.

The code is below.

Quote
void smallDelay() {
#ifdef TimeAlarms_h
  Alarm.delay(100); // Allows interrupts
#else
  delay(100);
#endif
}

#ifdef TimeAlarms_h
void MidnightAlarm(){ 
  // Serial.println("It's midnight");
  int diffTITH =0 ;
  for (byte i=0; i<sizeof(dtTI24); i++) {
    if (dtTI24 && dtTH24) diffTITH += dtTI24-dtTH24;   // diff=240/deg
    else { diffTITH=0; break; }
  }
  if (millis()>1000UL*3600*24) dtAnalogConfig[5]+= diffTITH /80 ; // scaled in 1/3 degrees at first
 
  // Replace by semaphore getRegister(REGI_ANALOGCONFIG)->getData(); // To check, changes only after min 1 day without reset
  if (day()<sizeof(dtSamples)) dtSamples[day()]=diffTITH /80;
}
#endif


 // and later

#ifdef TimeAlarms_h
  Alarm.alarmRepeat(0,0,0, MidnightAlarm);  // Midnight every day
#endif


#ifdef TimeAlarms_h
  Alarm.delay(1000L*loopTime - (1100+400*ADCstab));  // Sleep till txInterval, enabling alarms
#else
  delay(1000L*loopTime - (1100+400*ADCstab));  // Sleep till txInterval
#endif 
Commenting the midnight alarm part (i.e. only keeping the include and the replacement of delay by alarm.delay) will only "save" 200 bytes. Is there a logical/simple justification for such a large memory usage in EEPROM ?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: aarg on Jan 14, 2018, 07:42 pm
Maybe it takes that amount of code to implement the functionality... did you look at the source?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: marinbnm on Jul 15, 2018, 08:35 pm
If i want to see what day/hour/minute/sec will be after some time in past or future i use:

TimeSpan operator+(const TimeSpan& right);

But, what if i know dates like 12/07/2018 18:00 and is there function to calculate how much houres passed from that time till now.time()?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: DKWatson on Jul 15, 2018, 08:56 pm
All modern (computer-based) timing uses Unix time which is a 32-bit value in seconds since 00:00 Jan 1, 1970. For the convenience of humans, this value is converted into something they understand. Underneath it all remains the base time that can be added to, subtracted from, up to you, just treat it as a long variable. Google unix time and you'll find heaps of stuff on how to play with it.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: njotha on Sep 10, 2018, 10:24 am
Hi,
I'm trying to localize the strftime() output to German, but setlocale (LC_ALL, "de_DE") has no effect at all. Aunt Google has many answers for php, but no help for arduino. I'm including time.h and locale.h.

It's for the Heltec WiFi Kit 32 with OLED display

      setlocale (LC_ALL, "");
      setlocale (LC_ALL, "de_DE"); // or "de_DE.UTF8"
      struct tm * tmPointer = localtime(& tvTimeValue.tv_sec);
      // Display the date.
     
      strftime(chBuffer, sizeof(chBuffer), "%A",  tmPointer); 
      u8g2.setFont(u8g2_font_9x15_tr);
      u8g2.drawStr(64 - (u8g2.getStrWidth(chBuffer) / 2), 0, chBuffer);
 
      strftime(chBuffer, sizeof(chBuffer), "%d. %B",  tmPointer);   
      u8g2.setFont(u8g2_font_9x15_tr);
      u8g2.drawStr(64 - (u8g2.getStrWidth(chBuffer) / 2), 18, chBuffer);

deliver the English names for days of the week and for months - I'd very much like to see the German ones.

Any help would be welcome.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: odometer on Sep 10, 2018, 10:56 am
deliver the English names for days of the week and for months - I'd very much like to see the German ones.

Any help would be welcome.
That's what happens when you use (relatively) high-level libraries written by someone else.

If you can get at the numeric month, you can use it as an index to an array with the month names, and use that. You can use a similar trick for the day of the week.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: jsinghvirdi on Oct 31, 2018, 05:06 pm
How to set Alarm.alarmRepeat() from out side functions.

I am trying to set Alarm With LCD and Keypad but not able to do the same.

Please let me know how i can set Alarm parameters in other functions.

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Oct 31, 2018, 05:23 pm
Quote
How to set Alarm.alarmRepeat() from out side functions.
You can't call that method from outside a function.

Quote
I am trying to set Alarm With LCD and Keypad but not able to do the same.
Must be something wrong with your code. Posting your code using a zero point font was silly.

Quote
Please let me know how i can set Alarm parameters in other functions.
Exactly like you would in the "magic" functions setup() and loop().
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: jsinghvirdi on Oct 31, 2018, 06:25 pm
Sorry, my question is is it possible to create Alarm from other functions instead of setup() or loop() functions.

Like This :

void SetTimer(){

 Alarm.alarmRepeat(8,30,0, MorningAlarm);

}

Instead Of :

void setup(){

 Alarm.alarmRepeat(8,30,0, MorningAlarm);

}
You can't call that method from outside a function.
Must be something wrong with your code. Posting your code using a zero point font was silly.
Exactly like you would in the "magic" functions setup() and loop().
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Oct 31, 2018, 07:08 pm
Quote
is it possible to create Alarm from other functions instead of setup() or loop() functions.
Yes. There is nothing special about the setup() and loop() functions when it comes to setting up alarms.

Of course, you could have just tried it for yourself.  If you did try and it failed then post your code here for help.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: jsinghvirdi on Nov 01, 2018, 06:50 pm
Thanks UKHeliBob.

I got it and now its working but i have another question:

When i am using setTime(12,41,50,1,1,11); function in setup(), all working fine but if i did not use it no alarm will works.

Means:

I have implemented code to set Time by using setTime(12,41,50,1,1,11); and program to arduino mega, at this time clock shows exact time 12:41:50

but when i commented the setTime() line and reprogram the arduino. Now what happened the clock shows 00:00:00

On every reset or restart the arduino time clock shown me 00:00:00 and alarm is not working.


So i have wright code for Set Clock, now after set Clock successfully the time will shown exact the updated time, but when i restart the arduino the clock will again starts from 00:00:00.

Please help me....
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cattledog on Nov 01, 2018, 07:15 pm
Quote
So i have wright code for Set Clock, now after set Clock successfully the time will shown exact the updated time, but when i restart the arduino the clock will again starts from 00:00:00.

Please help me....
Your code to set the time is just referencing the Time library, which uses the the internal Arduino millis() function, to some outside time.  The Arduino will not remember this setting through powercycles/restarts. The internal millis() function will restart at 0 which the Time library interprets as 00:00:00.

It sounds like you want to use a Real Time Clock(RTC) hardware device if you want to remember the actual time through restarts. The DS3231 is a good one.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: ayawatson on Nov 17, 2018, 03:01 pm
Hi,

I would like to display the remaining value before the next timer repeats itself.

So far I've managed to execute a function based on a timer, however I really struggle to find a way to display remaining time.

Here is the code I use (based on the great examples provided with the library).

I could really use some help.

Thanks




Code: [Select]
#include <TimeLib.h>
#include <TimeAlarms.h>

AlarmId id;

void setup() {
  Serial.begin(115200);
  while (!Serial) ; // wait for Arduino Serial Monitor

  // create timers, to trigger relative to when they're created
  float repeatInDays = 0.00004;
  Serial.println("Repeat Cycle value in days is :");
  Serial.println(repeatInDays);
  long daysToSeconds = repeatInDays * 86400;
  Serial.println("Repeat Cycle value in Seconds is :");
  Serial.println(daysToSeconds);
 
  Alarm.timerRepeat(daysToSeconds, Repeats);           // timer

}

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


void Repeats() {
  Serial.println("Triggered");
}






Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Nov 17, 2018, 03:35 pm
Have you looked at the low level functions referenced in the readme for the library ?

The read(ID) function may be of help but I have never investigated it.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cattledog on Nov 17, 2018, 04:25 pm
The function you want is Alarm.getNextTrigger().
Code: [Select]
// returns the absolute time of the next scheduled alarm, or 0 if none
     time_t TimeAlarmsClass::getNextTrigger()
     {
     time_t nextTrigger = 0xffffffff;  // the max time value
     
        for(uint8_t id = 0; id < dtNBR_ALARMS; id++)
        {
          if(isAllocated(id) )
          {
        if(Alarm[id].nextTrigger <  nextTrigger)
       nextTrigger = Alarm[id].nextTrigger;
          }     
    }
        return nextTrigger == 0xffffffff ? 0 : nextTrigger; 
     }


Code: [Select]
#include <TimeLib.h>
#include <TimeAlarms.h>

AlarmId id;

void setup() {
  Serial.begin(115200);
  while (!Serial) ; // wait for Arduino Serial Monitor

  // create timers, to trigger relative to when they're created
  //float repeatInDays = 0.00004;
  float repeatInDays = 0.0004;
  Serial.println("Repeat Cycle value in days is :");
  Serial.println(repeatInDays);
  long daysToSeconds = repeatInDays * 86400;
  Serial.println("Repeat Cycle value in Seconds is :");
  Serial.println(daysToSeconds);

  Alarm.timerRepeat(daysToSeconds, Repeats);           // timer

}

void loop() {
  //digitalClockDisplay();
  Serial.print("Remaining Seconds = ");
  Serial.println(Alarm.getNextTrigger() - now());
  Alarm.delay(1000); // wait one second between clock display
}


void Repeats() {
  Serial.println("Triggered");
}


Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: ayawatson on Nov 18, 2018, 01:06 am
Thank you, it works perfectly.

Code: [Select]
#include <TimeLib.h>
#include <TimeAlarms.h>

AlarmId id;

void setup() {
  Serial.begin(115200);
  while (!Serial) ; // wait for Arduino Serial Monitor

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


  // create timers, to trigger relative to when they're created
  Alarm.timerRepeat(5, Repeats);           // timer for every 15 seconds

}

void loop() {
  Serial.println("Time right now");
  digitalClockDisplay();
  Serial.println("Next trigger time");
  triggerTimeDisplay();
  Alarm.delay(1000); // wait one second between clock display
}


void Repeats() {
  Serial.println(" ");
  Serial.println("TRIGGER");
  Serial.println(" ");
 
 

}




void digitalClockDisplay() {
  // digital clock display of the time
  Serial.print(day());
  Serial.print("/");
  Serial.print(month());
  Serial.print("/");
  Serial.println(year());
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.println();
}

void triggerTimeDisplay() {
  Serial.print(day(Alarm.getNextTrigger()));
  Serial.print("/");
  Serial.print(month(Alarm.getNextTrigger()));
  Serial.print("/");
  Serial.println(year(Alarm.getNextTrigger()));
 
  Serial.print(hour(Alarm.getNextTrigger()));
  printDigits(minute(Alarm.getNextTrigger()));
  printDigits(second(Alarm.getNextTrigger()));
  Serial.println();
}

void printDigits(int digits) {
  Serial.print(":");
  if (digits < 10)
    Serial.print('0');
  Serial.print(digits);
}
Title: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: mbenitez01 on Jan 02, 2019, 09:03 pm
all I get (tryng to compile) is following error...

collect2.exe: error: ld returned 1 exit status
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Jan 02, 2019, 10:04 pm
No code equals no help I am afraid
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: waqaspak on Jan 22, 2019, 10:45 pm
Alarm.alarmRepeat(8,30,0, switchON);  // 8:30am every day
Alarm.alarmRepeat(17,45,0,switchOFF);  // 5:45pm every day


my goal is to keep the switch on between 8:30am to 5:45pm and off otherwise
the problem is when my arduino does not have power supply at 8:30am it does not make the switchON because it has missed its alarm, when my arduino gets power at 8:45am or something,the switch is not ON.
any suggestion plz help
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Jan 22, 2019, 11:17 pm
If the Arduino is turned on after 08:30 then call the switchON() function from setup()
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: waqaspak on Jan 23, 2019, 10:07 am
If the Arduino is turned on after 08:30 then call the switchON() function from setup()

If I do that then how come timealarms.h library useful to me then I can also do it without timealarms.h

Plus in my project there are so many scheduled functions for which timealarms.h is very good and important

I need something to call the missed alarams by timealarms.h
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Jan 23, 2019, 12:00 pm
Quote
how come timealarms.h library useful to me then I can also do it without timealarms.h
You can do what you want without using TimeAlarms by checking the time from the RTC yourself

Quote
in my project there are so many scheduled functions for which timealarms.h is very good and important
Note that unless you have made a change to TimeAlarms.h to increase the dtNBR_ALARMS constant then only 6 alarms can be active at a time.

Quote
I need something to call the missed alarams by timealarms.h
In the other thread where you posted the problem it was suggested that when an alarm is triggered that you write a flag to EEPROM that can be read at startup to determine whether each alarm had been triggered or not.  This seems to be a sensible suggestion.

It may also be possible to determine that an alarm has been missed by using the Alarm.read() function but I have never used it.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: MBC99 on Jan 30, 2019, 04:01 pm
Hi there.
I'm currently working on a project to control the heating system on my home (link to the thread: http://forum.arduino.cc/index.php?topic=572413.0)
Now I'm on the final stage where I use the TimeAlarms to turn on or off the DHW tank at specific times.
I'm using DS3231RTC.h library.
To start with something easy I have used the existing example from the TimeAlarms and added the DS3231 part:
Code: [Select]
void setup() {
  Serial.begin(9600);
  while (!Serial) ; // wait for Arduino Serial Monitor
  setSyncProvider(RTC.get);   // the function to get the time from the RTC
  if (timeStatus() != timeSet)
    Serial.println("Unable to sync with the RTC");
  else
    Serial.println("RTC has set the system time");

  setTime(9, 29, 45, 1, 1, 11);
  RTC.set(now());
 
  // create the alarms, to trigger at specific times
  Alarm.alarmRepeat(9, 30, 0, onProg);
}

void onProg()
{
  Serial.print("Success");
}


Once this was working I tried adding the code to my code project (I only attach the setup(), if you consider that the rest of the code is needed ther's no problem, but the code is long and the time part is short):

Code: [Select]
void setup() {
  Serial.begin(9600);

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

  pinMode(PINACS, OUTPUT);
  pinMode(PINCALE, OUTPUT);
  pinMode(PINFAT, OUTPUT);
  pinMode(PINCALDERA, OUTPUT);
  pinMode(PINTERMOSTAT, INPUT_PULLUP);
  pinMode(PINBOMBACIR, INPUT_PULLUP);
  pinMode(PINTERMOFAT, INPUT_PULLUP);
  termostatActiu = false;
  canviEstat = false;
  ACSON = false;

  sensors.begin();
  sensors.setResolution(ACS, resolution);

  sensors.setWaitForConversion(false);
  sensors.requestTemperatures();

  delayInMillis = 750 / (1 << (12 - resolution));
  lastTempRequest = millis();

  setTime(9, 29, 40, 1, 1, 2019);
  RTC.set(now());

  Alarm.alarmRepeat(9, 30, 0, onProg);
  Alarm.alarmRepeat(14, 0, 0, offProg);
  Alarm.alarmRepeat(dowMonday , 16, 0, 0, onProg);
  Alarm.alarmRepeat(dowTuesday , 16, 0, 0, onProg);
  Alarm.alarmRepeat(dowWednesday , 16, 0, 0, onProg);
  Alarm.alarmRepeat(dowThursday , 16, 0, 0, onProg);
  Alarm.alarmRepeat(dowFriday , 16, 0, 0, onProg);
  Alarm.alarmRepeat(dowSaturday , 16, 0, 0, onProg);
  Alarm.alarmRepeat(19, 30, 0, offProg);
  Alarm.alarmRepeat(23, 0, 0, offProg);
  Alarm.timerRepeat(15, onProg);
 
  joystickBtns.begin();
  pinMode(LED_BUILTIN, OUTPUT);
  Wire.begin();
  oled.begin(&Adafruit128x64, OLED_I2C_ADDRESS); //check config
  oled.setFont(menuFont);
  oled.clear();
}


To keep things simple the onProg method is as follows:
Code: [Select]
void onProg()
{
  Serial.print("Success");
}


With all these I think the alarm should be trigered, but it doesn't.
On loop() I've added this:
Code: [Select]
Serial.print(hour());
  Serial.print("\t");
  Serial.print(minute());
  Serial.print("\t");
  Serial.println(second());


In order to see the time and make sure it works; it does. The time sets up to what I've put on the setup(), the problem is that at 9:30 the alarm doesn't trigger...
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Jan 30, 2019, 04:15 pm
Have you read the part about there being a limit on the number of timers you can set? Have you made the appropriate changes needed to support the number of timers you are trying to use?

Why DO you need to use this library? Having the Arduino do something at the same time every day is challenging without a RTC. With one, it is trivial.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: MBC99 on Jan 30, 2019, 04:22 pm
Have you read the part about there being a limit on the number of timers you can set? Have you made the appropriate changes needed to support the number of timers you are trying to use?

No, I have realised this mistake while I was looking 3 posts above mine. However, I've reduced the alarms to one (only the 9:30 one) and it still doesen't work:
Code: [Select]
void setup() {
  Serial.begin(9600);

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

  pinMode(PINACS, OUTPUT);
  pinMode(PINCALE, OUTPUT);
  pinMode(PINFAT, OUTPUT);
  pinMode(PINCALDERA, OUTPUT);
  pinMode(PINTERMOSTAT, INPUT_PULLUP);
  pinMode(PINBOMBACIR, INPUT_PULLUP);
  pinMode(PINTERMOFAT, INPUT_PULLUP);
  termostatActiu = false;
  canviEstat = false;
  ACSON = false;

  sensors.begin();
  sensors.setResolution(ACS, resolution);

  sensors.setWaitForConversion(false);
  sensors.requestTemperatures();

  delayInMillis = 750 / (1 << (12 - resolution));
  lastTempRequest = millis();

  setTime(9, 29, 40, 1, 1, 2019);
  RTC.set(now());

  Alarm.alarmRepeat(9, 30, 0, onProg);
  /*Alarm.alarmRepeat(14, 0, 0, offProg);
  Alarm.alarmRepeat(dowMonday , 16, 0, 0, onProg);
  Alarm.alarmRepeat(dowTuesday , 16, 0, 0, onProg);
  Alarm.alarmRepeat(dowWednesday , 16, 0, 0, onProg);
  Alarm.alarmRepeat(dowThursday , 16, 0, 0, onProg);
  Alarm.alarmRepeat(dowFriday , 16, 0, 0, onProg);
  Alarm.alarmRepeat(dowSaturday , 16, 0, 0, onProg);
  Alarm.alarmRepeat(19, 30, 0, offProg);
  Alarm.alarmRepeat(23, 0, 0, offProg);
  Alarm.timerRepeat(15, onProg);*/
 
  joystickBtns.begin();
  pinMode(LED_BUILTIN, OUTPUT);
  Wire.begin();
  oled.begin(&Adafruit128x64, OLED_I2C_ADDRESS); //check config
  oled.setFont(menuFont);
  oled.clear();
}


Why DO you need to use this library? Having the Arduino do something at the same time every day is challenging without a RTC. With one, it is trivial.
I think I'm not following you. Do you mean that I could use the integrated alarms on the RTC? If so it's kind of impossible because it only has two alarms.
Or do you mean to just hard-code this part rather than use TimeAlarms?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Jan 30, 2019, 04:25 pm
Quote
Or do you mean to just hard-code this part rather than use TimeAlarms?
Read the time from the RTC. If it is time to do something, do it. If not, don't.

The TimeAlarm class does take care of making sure that the thing to be done is done only once, when the time is right, so you'll need to deal with that, too.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: UKHeliBob on Jan 30, 2019, 04:26 pm
Have you used Alarm.delay() anywhere in your program
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Jan 30, 2019, 04:28 pm
I'd also read from the RTC after setting the time, just as a sanity check, to make sure that you have the correct number of values, in the correct order. If you are setting the time to 9:29, but the time that gets read after you do that is 255:255, well, something isn't right.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: cattledog on Jan 30, 2019, 04:29 pm
You have not used
Quote
Alarm.delay(milliseconds);
Alarms and Timers are only checks and their functions called when you use this delay function. You can pass 0 for minimal delay. This delay should be used instead of the normal Arduino delay(), for timely processing of alarms and timers.
Full documentation of the library is here
https://github.com/PaulStoffregen/TimeAlarms (https://github.com/PaulStoffregen/TimeAlarms)

Both the number of alarms issue and the use of alarm.delay() are covered in the Read Me section.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: MBC99 on Jan 30, 2019, 07:20 pm
Read the time from the RTC. If it is time to do something, do it. If not, don't.

The TimeAlarm class does take care of making sure that the thing to be done is done only once, when the time is right, so you'll need to deal with that, too.
So you say to just compare for example if programedHour==hour(), programmedMinute==minute() etc. then do something?

I will take a look at that

Have you used Alarm.delay() anywhere in your program
Alarm.dealay() not for sure.
However there's a 1ms delay, it's the only delay on the whole code. I have alredy taken care that OneWire doesen't use delays.

Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: MBC99 on Jan 30, 2019, 07:26 pm
I'd also read from the RTC after setting the time, just as a sanity check, to make sure that you have the correct number of values, in the correct order. If you are setting the time to 9:29, but the time that gets read after you do that is 255:255, well, something isn't right.
Do you mean to just this:
Code: [Select]
Serial.print(hour());
  Serial.print("\t");
  Serial.print(minute());
  Serial.print("\t");
  Serial.println(second());


just after setting the time?
I've tried it, the results are consistent and correct.
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: MBC99 on Jan 30, 2019, 07:33 pm
Ok, I feel very stupid. It was the freaking 1ms delay.
I knew they could interfer with the code, but come on, it's just 1ms  >:(

Thanks to all of you.


However I'll try to do what @PaulS has said. Because I'm at 96% capacity on my arduino nano...

One last question...
To change the number of alarms I have to modify the .h file:
Code: [Select]
#if defined(__AVR__)
#define dtNBR_ALARMS 6   // max is 255
#else
#define dtNBR_ALARMS 12  // assume non-AVR has more memory
#endif


I have to change the number 6 by the number of alarms I want, but what does the second line (the one with the 12) do?
Title: Re: Time and TimeAlarms Libraries – Ask here for help or suggestions
Post by: PaulS on Jan 30, 2019, 07:43 pm
Quote
I knew they could interfer with the code, but come on, it's just 1ms
It's not that they interfere with each other. The call to delay() in the Alarm class is the only way that the class has of knowing that ANY time has passed. That method could be called checkForTimePassing(), and maybe it would be more obvious that it needed to be called regularly.

Quote
but what does the second line (the one with the 12) do?
It sets the number of alarms on boards that do not have an AVR chip, such as the SAM32 boards. The ARM (non-AVR) boards have, in general, much more memory.