Time and TimeAlarms Libraries – Ask here for help or suggestions

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

/*
 * 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

TimeGPS_GLCD_Round1.ino (2.9 KB)

Time_Baro_R_H__GLCD_R1_2.ino (5.64 KB)

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

I'm not sure what you are asking here.

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

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":

/*
 * 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

  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.


  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.

  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.


  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:

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

Is this the cause it appears to be the address to the var fix age
"gps.get_datetime(NULL,NULL, &fix_age);"
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

Look at the prototype:

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

  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:

if(fix_age < 1000)

or:

if(*ptr_fix_age < 1000)

If you use the pointer you dereference it. If not, you don't.

jan_bl:
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 !

DateStrings.cpp (2.72 KB)

I believe the following page would benefit from some additional info - Arduino Playground - HomePage

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... :blush:

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

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:

#include <WProgram.h>

in Time.cpp:

#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!

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

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?

jaredc:
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:

#include <WProgram.h>

in Time.cpp:

#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!

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

Guy-Wittig:
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

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

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

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.

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

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

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!

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.