From f9e5f61353ff1dd6b5b3929076cdb594bba9dda2 Mon Sep 17 00:00:00 2001 From: andyduino Date: Thu, 24 Sep 2015 23:05:58 +0700 Subject: [PATCH] change to arduino mega 2560 --- MQTT-for-SIM900/MQTT-for-SIM900.ino | 74 +- libraries/DS1307RTC/DS1307RTC.cpp | 142 ++++ libraries/DS1307RTC/DS1307RTC.h | 37 + .../DS1307RTC/examples/ReadTest/ReadTest.ino | 49 ++ .../DS1307RTC/examples/SetTime/SetTime.ino | 75 ++ libraries/DS1307RTC/keywords.txt | 23 + libraries/DS1307RTC/library.properties | 10 + libraries/DS1307RTC/readme.txt | 7 + libraries/RTCTimer/.gitignore | 4 + libraries/RTCTimer/COPYING | 674 ++++++++++++++++++ libraries/RTCTimer/COPYING.LESSER | 165 +++++ libraries/RTCTimer/Readme.md | 11 + libraries/RTCTimer/examples/blink/blink.ino | 53 ++ libraries/RTCTimer/examples/blink2/blink2.ino | 152 ++++ .../sync_rtc_through_gprs.ino | 99 +++ libraries/RTCTimer/library.properties | 11 + libraries/RTCTimer/make-zip.sh | 25 + libraries/RTCTimer/src/RTCTimer.cpp | 155 ++++ libraries/RTCTimer/src/RTCTimer.h | 71 ++ libraries/Time/DateStrings.cpp | 97 +++ libraries/Time/Readme.txt | 131 ++++ libraries/Time/Time.cpp | 319 +++++++++ libraries/Time/Time.h | 144 ++++ .../SyncArduinoClock/SyncArduinoClock.pde | 78 ++ .../Processing/SyncArduinoClock/readme.txt | 9 + .../TimeArduinoDue/TimeArduinoDue.ino | 71 ++ libraries/Time/examples/TimeGPS/TimeGPS.ino | 87 +++ libraries/Time/examples/TimeNTP/TimeNTP.ino | 135 ++++ libraries/Time/examples/TimeRTC/TimeRTC.pde | 55 ++ .../Time/examples/TimeRTCLog/TimeRTCLog.pde | 107 +++ .../Time/examples/TimeRTCSet/TimeRTCSet.ino | 80 +++ .../Time/examples/TimeSerial/TimeSerial.ino | 81 +++ .../TimeSerialDateStrings.ino | 108 +++ .../Time/examples/TimeTeensy3/TimeTeensy3.ino | 78 ++ libraries/Time/keywords.txt | 33 + libraries/Time/library.json | 22 + libraries/Time/library.properties | 10 + libraries/TimeAlarms/TimeAlarms.cpp | 357 ++++++++++ libraries/TimeAlarms/TimeAlarms.h | 127 ++++ .../TimeAlarmExample/TimeAlarmExample.pde | 77 ++ libraries/TimeAlarms/keywords.txt | 25 + libraries/TimeAlarms/library.json | 16 + libraries/TimeAlarms/library.properties | 10 + libraries/TimeAlarms/readme.txt | 220 ++++++ 44 files changed, 4277 insertions(+), 37 deletions(-) create mode 100644 libraries/DS1307RTC/DS1307RTC.cpp create mode 100644 libraries/DS1307RTC/DS1307RTC.h create mode 100644 libraries/DS1307RTC/examples/ReadTest/ReadTest.ino create mode 100644 libraries/DS1307RTC/examples/SetTime/SetTime.ino create mode 100644 libraries/DS1307RTC/keywords.txt create mode 100644 libraries/DS1307RTC/library.properties create mode 100644 libraries/DS1307RTC/readme.txt create mode 100644 libraries/RTCTimer/.gitignore create mode 100644 libraries/RTCTimer/COPYING create mode 100644 libraries/RTCTimer/COPYING.LESSER create mode 100644 libraries/RTCTimer/Readme.md create mode 100644 libraries/RTCTimer/examples/blink/blink.ino create mode 100644 libraries/RTCTimer/examples/blink2/blink2.ino create mode 100644 libraries/RTCTimer/examples/sync_rtc_through_gprs/sync_rtc_through_gprs.ino create mode 100644 libraries/RTCTimer/library.properties create mode 100644 libraries/RTCTimer/make-zip.sh create mode 100644 libraries/RTCTimer/src/RTCTimer.cpp create mode 100644 libraries/RTCTimer/src/RTCTimer.h create mode 100644 libraries/Time/DateStrings.cpp create mode 100644 libraries/Time/Readme.txt create mode 100644 libraries/Time/Time.cpp create mode 100644 libraries/Time/Time.h create mode 100644 libraries/Time/examples/Processing/SyncArduinoClock/SyncArduinoClock.pde create mode 100644 libraries/Time/examples/Processing/SyncArduinoClock/readme.txt create mode 100644 libraries/Time/examples/TimeArduinoDue/TimeArduinoDue.ino create mode 100644 libraries/Time/examples/TimeGPS/TimeGPS.ino create mode 100644 libraries/Time/examples/TimeNTP/TimeNTP.ino create mode 100644 libraries/Time/examples/TimeRTC/TimeRTC.pde create mode 100644 libraries/Time/examples/TimeRTCLog/TimeRTCLog.pde create mode 100644 libraries/Time/examples/TimeRTCSet/TimeRTCSet.ino create mode 100644 libraries/Time/examples/TimeSerial/TimeSerial.ino create mode 100644 libraries/Time/examples/TimeSerialDateStrings/TimeSerialDateStrings.ino create mode 100644 libraries/Time/examples/TimeTeensy3/TimeTeensy3.ino create mode 100644 libraries/Time/keywords.txt create mode 100644 libraries/Time/library.json create mode 100644 libraries/Time/library.properties create mode 100644 libraries/TimeAlarms/TimeAlarms.cpp create mode 100644 libraries/TimeAlarms/TimeAlarms.h create mode 100644 libraries/TimeAlarms/examples/TimeAlarmExample/TimeAlarmExample.pde create mode 100644 libraries/TimeAlarms/keywords.txt create mode 100644 libraries/TimeAlarms/library.json create mode 100644 libraries/TimeAlarms/library.properties create mode 100644 libraries/TimeAlarms/readme.txt diff --git a/MQTT-for-SIM900/MQTT-for-SIM900.ino b/MQTT-for-SIM900/MQTT-for-SIM900.ino index 9b8052d..e4984b7 100644 --- a/MQTT-for-SIM900/MQTT-for-SIM900.ino +++ b/MQTT-for-SIM900/MQTT-for-SIM900.ino @@ -1,9 +1,7 @@ /* Very, very primitive. MQTT Test program to send data to a MQTT Server - V00 / 09th March 2013, omer sever, omers@tr.ibm.com initial version w/o valid IOC parameters - V01 / 10th March 2013, ates yurdakul, atesh@puaga.com modified for IOC parameters disabled GPS for simplicity @@ -20,10 +18,11 @@ #include #include -//#include +#include #include #include "DHT.h" +SoftwareSerial GPRS(10, 11); // RX, TX /* #include #include "TinyGPS.h" TinyGPS gps; @@ -87,27 +86,27 @@ int sentCount = 0; void setup() { pinMode(13, OUTPUT); - pinMode(14, OUTPUT); // GSM + pinMode(22, OUTPUT); // GSM digitalWrite(0, HIGH); Serial.begin(9600); //debug - Serial1.begin(19200); // GPRS module + GPRS.begin(9600); // GPRS module // gpss.begin(9600); dht.begin(); } void loop(){ - delay(20000);// wait for GPRS getting stable - - //for(int k=0;k++;k<2){ - get_AM2301_Data(); + + // digitalWrite(22,HIGH); + digitalWrite(13,HIGH); + delay(20000);// wait for GPRS getting stable + + //get_AM2301_Data(); get_water_temp(); - Serial.println("Checking if GPRS is ready"); - Serial1.println("AT"); + GPRS.println("AT"); delay(1000); gprsReady = isGPRSReady(); - if (gprsReady == true){ Serial.println("GPRS Ready"); String json = buildJson(); @@ -119,16 +118,16 @@ void loop(){ /* The arguments here are: clientID, IP, Port, Topic, Message */ - sendMQTTMessage("agrinode", "iot.eclipse.org", "1883", "agrinode01",jsonStr); + sendMQTTMessage("agrinode", "test.mosquitto.org", "1883", "agrinode01",jsonStr); + }//and of if +//digitalWrite(22,LOW); +digitalWrite(13,LOW); +delay(60000); - delay(10000); - //} //end of for - - while(1); } - +/* uint32_t parsedecimal(char *str) { uint32_t d = 0; while (str[0] != 0) { @@ -139,7 +138,7 @@ uint32_t parsedecimal(char *str) { str++; } return d; -} +}*/ void readline() { /*char c; @@ -159,10 +158,12 @@ void readline() { }*/ } boolean isGPRSReady(){ - Serial1.println("AT+CGATT?"); + GPRS.println("AT"); + GPRS.println("AT"); + GPRS.println("AT+CGATT?"); index = 0; - while (Serial1.available()){ - data1 = (char)Serial1.read(); + while (GPRS.available()){ + data1 = (char)GPRS.read(); Serial.write(data1); gprsStr[index++] = data1; } @@ -180,17 +181,17 @@ boolean isGPRSReady(){ } void sendMQTTMessage(char* clientId, char* brokerUrl, char* brokerPort, char* topic, char* message){ - Serial1.println("AT"); // Sends AT command to wake up cell phone + GPRS.println("AT"); // Sends AT command to wake up cell phone Serial.println("send AT to wake up GPRS"); delay(1000); // Wait a second - digitalWrite(13, HIGH); - Serial1.println("AT+CSTT=\"m-wap\",\"mms\",\"mms\""); // Puts phone into GPRS mode +// digitalWrite(13, HIGH); + GPRS.println("AT+CSTT=\"m-wap\",\"mms\",\"mms\""); // Puts phone into GPRS mode Serial.println("AT+CSTT=\"m-wap\",\"mms\",\"mms\""); delay(2000); // Wait a second - Serial1.println("AT+CIICR"); + GPRS.println("AT+CIICR"); Serial.println("AT+CIICR"); delay(2000); - Serial1.println("AT+CIFSR"); + GPRS.println("AT+CIFSR"); Serial.println("AT+CIFSR"); delay(2000); strcpy(atCommand, "AT+CIPSTART=\"TCP\",\""); @@ -198,38 +199,38 @@ void sendMQTTMessage(char* clientId, char* brokerUrl, char* brokerPort, char* to strcat(atCommand, "\",\""); strcat(atCommand, brokerPort); strcat(atCommand, "\""); - Serial1.println(atCommand); + GPRS.println(atCommand); Serial.println(atCommand); // Serial.println("AT+CIPSTART=\"TCP\",\"mqttdashboard.com\",\"1883\""); delay(2000); - Serial1.println("AT+CIPSEND"); + GPRS.println("AT+CIPSEND"); Serial.println("AT+CIPSEND"); delay(2000); mqttMessageLength = 16 + strlen(clientId); Serial.println(mqttMessageLength); mqtt_connect_message(mqttMessage, clientId); for (int j = 0; j < mqttMessageLength; j++) { - Serial1.write(mqttMessage[j]); // Message contents + GPRS.write(mqttMessage[j]); // Message contents Serial.write(mqttMessage[j]); // Message contents Serial.println(""); } - Serial1.write(byte(26)); // (signals end of message) + GPRS.write(byte(26)); // (signals end of message) Serial.println("Sent"); delay(10000); - Serial1.println("AT+CIPSEND"); + GPRS.println("AT+CIPSEND"); Serial.println("AT+CIPSEND"); delay(2000); mqttMessageLength = 4 + strlen(topic) + strlen(message); Serial.println(mqttMessageLength); mqtt_publish_message(mqttMessage, topic, message); for (int k = 0; k < mqttMessageLength; k++) { - Serial1.write(mqttMessage[k]); + GPRS.write(mqttMessage[k]); Serial.write((byte)mqttMessage[k]); } - Serial1.write(byte(26)); // (signals end of message) + GPRS.write(byte(26)); // (signals end of message) Serial.println("-------------Sent-------------"); // Message contents delay(5000); - Serial1.println("AT+CIPCLOSE"); + GPRS.println("AT+CIPCLOSE"); Serial.println("AT+CIPCLOSE"); delay(2000); } @@ -244,7 +245,7 @@ void get_AM2301_Data() { Serial.println("Failed to read from DHT sensor"); Air_Humidity=0; Air_Temp=0; - return; + // return; } } @@ -315,4 +316,3 @@ String buildJson() { data+="}"; return data; } - diff --git a/libraries/DS1307RTC/DS1307RTC.cpp b/libraries/DS1307RTC/DS1307RTC.cpp new file mode 100644 index 0000000..7d0f1cf --- /dev/null +++ b/libraries/DS1307RTC/DS1307RTC.cpp @@ -0,0 +1,142 @@ +/* + * DS1307RTC.h - library for DS1307 RTC + + Copyright (c) Michael Margolis 2009 + This library is intended to be uses with Arduino Time.h library functions + + The library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + 30 Dec 2009 - Initial release + 5 Sep 2011 updated for Arduino 1.0 + */ + +#include +#include "DS1307RTC.h" + +#define DS1307_CTRL_ID 0x68 + +DS1307RTC::DS1307RTC() +{ + Wire.begin(); +} + +// PUBLIC FUNCTIONS +time_t DS1307RTC::get() // Aquire data from buffer and convert to time_t +{ + tmElements_t tm; + if (read(tm) == false) return 0; + return(makeTime(tm)); +} + +bool DS1307RTC::set(time_t t) +{ + tmElements_t tm; + breakTime(t, tm); + tm.Second |= 0x80; // stop the clock + write(tm); + tm.Second &= 0x7f; // start the clock + write(tm); +} + +// Aquire data from the RTC chip in BCD format +bool DS1307RTC::read(tmElements_t &tm) +{ + uint8_t sec; + Wire.beginTransmission(DS1307_CTRL_ID); +#if ARDUINO >= 100 + Wire.write((uint8_t)0x00); +#else + Wire.send(0x00); +#endif + if (Wire.endTransmission() != 0) { + exists = false; + return false; + } + exists = true; + + // request the 7 data fields (secs, min, hr, dow, date, mth, yr) + Wire.requestFrom(DS1307_CTRL_ID, tmNbrFields); + if (Wire.available() < tmNbrFields) return false; +#if ARDUINO >= 100 + sec = Wire.read(); + tm.Second = bcd2dec(sec & 0x7f); + tm.Minute = bcd2dec(Wire.read() ); + tm.Hour = bcd2dec(Wire.read() & 0x3f); // mask assumes 24hr clock + tm.Wday = bcd2dec(Wire.read() ); + tm.Day = bcd2dec(Wire.read() ); + tm.Month = bcd2dec(Wire.read() ); + tm.Year = y2kYearToTm((bcd2dec(Wire.read()))); +#else + sec = Wire.receive(); + tm.Second = bcd2dec(sec & 0x7f); + tm.Minute = bcd2dec(Wire.receive() ); + tm.Hour = bcd2dec(Wire.receive() & 0x3f); // mask assumes 24hr clock + tm.Wday = bcd2dec(Wire.receive() ); + tm.Day = bcd2dec(Wire.receive() ); + tm.Month = bcd2dec(Wire.receive() ); + tm.Year = y2kYearToTm((bcd2dec(Wire.receive()))); +#endif + if (sec & 0x80) return false; // clock is halted + return true; +} + +bool DS1307RTC::write(tmElements_t &tm) +{ + Wire.beginTransmission(DS1307_CTRL_ID); +#if ARDUINO >= 100 + Wire.write((uint8_t)0x00); // reset register pointer + Wire.write(dec2bcd(tm.Second)) ; + Wire.write(dec2bcd(tm.Minute)); + Wire.write(dec2bcd(tm.Hour)); // sets 24 hour format + Wire.write(dec2bcd(tm.Wday)); + Wire.write(dec2bcd(tm.Day)); + Wire.write(dec2bcd(tm.Month)); + Wire.write(dec2bcd(tmYearToY2k(tm.Year))); +#else + Wire.send(0x00); // reset register pointer + Wire.send(dec2bcd(tm.Second)) ; + Wire.send(dec2bcd(tm.Minute)); + Wire.send(dec2bcd(tm.Hour)); // sets 24 hour format + Wire.send(dec2bcd(tm.Wday)); + Wire.send(dec2bcd(tm.Day)); + Wire.send(dec2bcd(tm.Month)); + Wire.send(dec2bcd(tmYearToY2k(tm.Year))); +#endif + if (Wire.endTransmission() != 0) { + exists = false; + return false; + } + exists = true; + return true; +} + +// PRIVATE FUNCTIONS + +// Convert Decimal to Binary Coded Decimal (BCD) +uint8_t DS1307RTC::dec2bcd(uint8_t num) +{ + return ((num/10 * 16) + (num % 10)); +} + +// Convert Binary Coded Decimal (BCD) to Decimal +uint8_t DS1307RTC::bcd2dec(uint8_t num) +{ + return ((num/16 * 10) + (num % 16)); +} + +bool DS1307RTC::exists = false; + +DS1307RTC RTC = DS1307RTC(); // create an instance for the user + diff --git a/libraries/DS1307RTC/DS1307RTC.h b/libraries/DS1307RTC/DS1307RTC.h new file mode 100644 index 0000000..b71abfd --- /dev/null +++ b/libraries/DS1307RTC/DS1307RTC.h @@ -0,0 +1,37 @@ +/* + * DS1307RTC.h - library for DS1307 RTC + * This library is intended to be uses with Arduino Time.h library functions + */ + +#ifndef DS1307RTC_h +#define DS1307RTC_h + +#include + +// library interface description +class DS1307RTC +{ + // user-accessible "public" interface + public: + DS1307RTC(); + static time_t get(); + static bool set(time_t t); + static bool read(tmElements_t &tm); + static bool write(tmElements_t &tm); + static bool chipPresent() { return exists; } + + private: + static bool exists; + static uint8_t dec2bcd(uint8_t num); + static uint8_t bcd2dec(uint8_t num); +}; + +#ifdef RTC +#undef RTC // workaround for Arduino Due, which defines "RTC"... +#endif + +extern DS1307RTC RTC; + +#endif + + diff --git a/libraries/DS1307RTC/examples/ReadTest/ReadTest.ino b/libraries/DS1307RTC/examples/ReadTest/ReadTest.ino new file mode 100644 index 0000000..52ac566 --- /dev/null +++ b/libraries/DS1307RTC/examples/ReadTest/ReadTest.ino @@ -0,0 +1,49 @@ +#include +#include +#include + +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); +} diff --git a/libraries/DS1307RTC/examples/SetTime/SetTime.ino b/libraries/DS1307RTC/examples/SetTime/SetTime.ino new file mode 100644 index 0000000..8d5e67d --- /dev/null +++ b/libraries/DS1307RTC/examples/SetTime/SetTime.ino @@ -0,0 +1,75 @@ +#include +#include +#include + +const char *monthName[12] = { + "Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" +}; + +tmElements_t tm; + +void setup() { + bool parse=false; + bool config=false; + + // get the date and time the compiler was run + if (getDate(__DATE__) && getTime(__TIME__)) { + parse = true; + // and configure the RTC with this info + if (RTC.write(tm)) { + config = true; + } + } + + Serial.begin(9600); + while (!Serial) ; // wait for Arduino Serial Monitor + delay(200); + if (parse && config) { + Serial.print("DS1307 configured Time="); + Serial.print(__TIME__); + Serial.print(", Date="); + Serial.println(__DATE__); + } else if (parse) { + Serial.println("DS1307 Communication Error :-{"); + Serial.println("Please check your circuitry"); + } else { + Serial.print("Could not parse info from the compiler, Time=\""); + Serial.print(__TIME__); + Serial.print("\", Date=\""); + Serial.print(__DATE__); + Serial.println("\""); + } +} + +void loop() { +} + +bool getTime(const char *str) +{ + int Hour, Min, Sec; + + if (sscanf(str, "%d:%d:%d", &Hour, &Min, &Sec) != 3) return false; + tm.Hour = Hour; + tm.Minute = Min; + tm.Second = Sec; + return true; +} + +bool getDate(const char *str) +{ + char Month[12]; + int Day, Year; + uint8_t monthIndex; + + if (sscanf(str, "%s %d %d", Month, &Day, &Year) != 3) return false; + for (monthIndex = 0; monthIndex < 12; monthIndex++) { + if (strcmp(Month, monthName[monthIndex]) == 0) break; + } + if (monthIndex >= 12) return false; + tm.Day = Day; + tm.Month = monthIndex + 1; + tm.Year = CalendarYrToTm(Year); + return true; +} + diff --git a/libraries/DS1307RTC/keywords.txt b/libraries/DS1307RTC/keywords.txt new file mode 100644 index 0000000..2fe86ca --- /dev/null +++ b/libraries/DS1307RTC/keywords.txt @@ -0,0 +1,23 @@ +####################################### +# Syntax Coloring Map For DS1307RTC +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +####################################### +# Methods and Functions (KEYWORD2) +####################################### +get KEYWORD2 +set KEYWORD2 +read KEYWORD2 +write KEYWORD2 +chipPresent KEYWORD2 +####################################### +# Instances (KEYWORD2) +####################################### +RTC KEYWORD2 +####################################### +# Constants (LITERAL1) +####################################### diff --git a/libraries/DS1307RTC/library.properties b/libraries/DS1307RTC/library.properties new file mode 100644 index 0000000..f39b262 --- /dev/null +++ b/libraries/DS1307RTC/library.properties @@ -0,0 +1,10 @@ +name=DS1307RTC +version=1.4 +author=Michael Margolis +maintainer=Paul Stoffregen +sentence=Use a DS1307 Real Time Clock chip with the Time library +paragraph= +category=Timing +url=http://playground.arduino.cc/code/time +architectures=* + diff --git a/libraries/DS1307RTC/readme.txt b/libraries/DS1307RTC/readme.txt new file mode 100644 index 0000000..5978295 --- /dev/null +++ b/libraries/DS1307RTC/readme.txt @@ -0,0 +1,7 @@ +Readme file for DS1307RTC Library + +The DS1307RTC library is provided to demonstrate the Arduino Time library. + +See the TimeRTC example sketches privided with the Time library download for usage + + diff --git a/libraries/RTCTimer/.gitignore b/libraries/RTCTimer/.gitignore new file mode 100644 index 0000000..63eb389 --- /dev/null +++ b/libraries/RTCTimer/.gitignore @@ -0,0 +1,4 @@ +*~ +.*.swp +*.zip +.DS_Store diff --git a/libraries/RTCTimer/COPYING b/libraries/RTCTimer/COPYING new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/libraries/RTCTimer/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/libraries/RTCTimer/COPYING.LESSER b/libraries/RTCTimer/COPYING.LESSER new file mode 100644 index 0000000..65c5ca8 --- /dev/null +++ b/libraries/RTCTimer/COPYING.LESSER @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/libraries/RTCTimer/Readme.md b/libraries/RTCTimer/Readme.md new file mode 100644 index 0000000..6182f45 --- /dev/null +++ b/libraries/RTCTimer/Readme.md @@ -0,0 +1,11 @@ +This is an Arduino library to easily perform scheduled tasks. The timing +is done by looking at an RTC and an update function that must be called +from the Arduino main loop. + +This library was inspired by Simon Monk's Timer. + +The reason for this library is that it uses an RTC (e.g. DS3231) to supply +a clock. It will remain functional when the MCU goes to "deep sleep". + +The biggest difference with Timer is that RTCTimer uses the units that RTC +can give, which is most likely seconds (not milliseconds). diff --git a/libraries/RTCTimer/examples/blink/blink.ino b/libraries/RTCTimer/examples/blink/blink.ino new file mode 100644 index 0000000..42fc138 --- /dev/null +++ b/libraries/RTCTimer/examples/blink/blink.ino @@ -0,0 +1,53 @@ +/* + * This example shows how to schedule some work at + * regular intervals. + * + * Notice that the "epoch" of the RTC is used and the time units + * are in seconds. (The Timer library works with millis() so its + * time units are milliseconds. + */ + +#include + +#include + +RTCTimer timer; // Instantiate the timer + +const int led = 6; + +void setup() +{ + pinMode(led, OUTPUT); + + // Do the work every 5 seconds + timer.every(5, toggleLed); + + // Instruct the RTCTimer how to get the current timestamp + timer.setNowCallback(getNow); +} + +void loop() +{ + timer.update(); +} + + + +void toggleLed(uint32_t ts) +{ + static bool on; + + on = !on; + digitalWrite(led, on); +} + +/* + * Return the current timestamp + * + * This is a general purpose wrapper function to get the current timestamp. + * It can also be used for timer.setNowCallback + */ +uint32_t getNow() +{ + return rtc.now().getEpoch(); +} diff --git a/libraries/RTCTimer/examples/blink2/blink2.ino b/libraries/RTCTimer/examples/blink2/blink2.ino new file mode 100644 index 0000000..c1be37f --- /dev/null +++ b/libraries/RTCTimer/examples/blink2/blink2.ino @@ -0,0 +1,152 @@ +/* + * This example shows how to schedule some work at + * regular intervals. + * + * This example is a bit more advanced. It uses the WDT as + * an interrupt to wake up from deep sleep. During the wake + * up it does the RTCTimer.update so that it can do scheduled + * tasks. The RTC continues to run during the deep sleep so the + * timing remains accurate. And at the same time the power + * consumption is as low as possible. + * + * Notice that the "epoch" of the RTC is used and the time units + * are in seconds. (The Timer library works with millis() so its + * time units are milliseconds. + */ + +// We need these includes to program the WDT +#include +#include + +#include + +#include + +RTCTimer timer; // Instantiate the timer + +const int led = 6; + +bool hz_flag; + +void setup() +{ + pinMode(led, OUTPUT); + + // Do the work every 5 seconds + timer.every(5, toggleLed); + + // Instruct the RTCTimer how to get the current timestamp + timer.setNowCallback(getNow); + + setupWatchdog(); + + interrupts(); +} + +void loop() +{ + if (hz_flag) { + hz_flag = false; + wdt_reset(); + WDTCSR |= _BV(WDIE); + } + + timer.update(); + + systemSleep(); +} + + + +void toggleLed(uint32_t ts) +{ + static bool on; + + on = !on; + digitalWrite(led, on); +} + +/* + * Return the current timestamp + * + * This is a general purpose wrapper function to get the current timestamp. + * It can also be used for timer.setNowCallback + */ +uint32_t getNow() +{ + return rtc.now().getEpoch(); +} + + + +//######### watchdog and system sleep ############# +void systemSleep() +{ + ADCSRA &= ~_BV(ADEN); // ADC disabled + + /* + * Possible sleep modes are (see sleep.h): + #define SLEEP_MODE_IDLE (0) + #define SLEEP_MODE_ADC _BV(SM0) + #define SLEEP_MODE_PWR_DOWN _BV(SM1) + #define SLEEP_MODE_PWR_SAVE (_BV(SM0) | _BV(SM1)) + #define SLEEP_MODE_STANDBY (_BV(SM1) | _BV(SM2)) + #define SLEEP_MODE_EXT_STANDBY (_BV(SM0) | _BV(SM1) | _BV(SM2)) + */ + set_sleep_mode(SLEEP_MODE_PWR_DOWN); + sleep_mode(); + + ADCSRA |= _BV(ADEN); // ADC enabled +} + + +// The watchdog timer is used to make timed interrupts +#if 0 +// Both WDE and WDIE are set!! +// Note from the doc: "Executing the corresponding interrupt +// vector will clear WDIE and WDIF automatically by hardware +// (the Watchdog goes to System Reset Mode) +#define my_wdt_enable(value) \ +__asm__ __volatile__ ( \ + "in __tmp_reg__,__SREG__" "\n\t" \ + "cli" "\n\t" \ + "wdr" "\n\t" \ + "sts %0,%1" "\n\t" \ + "out __SREG__,__tmp_reg__" "\n\t" \ + "sts %0,%2" "\n\t" \ + : /* no outputs */ \ + : "M" (_SFR_MEM_ADDR(_WD_CONTROL_REG)), \ + "r" (_BV(_WD_CHANGE_BIT) | _BV(WDE)), \ + "r" ((uint8_t) (((value & 0x08) ? _WD_PS3_MASK : 0x00) | \ + _BV(WDE) | _BV(WDIE) | (value & 0x07)) ) \ + : "r0" \ +) +#else +// Only WDIE is set!! +#define my_wdt_enable(value) \ +__asm__ __volatile__ ( \ + "in __tmp_reg__,__SREG__" "\n\t" \ + "cli" "\n\t" \ + "wdr" "\n\t" \ + "sts %0,%1" "\n\t" \ + "out __SREG__,__tmp_reg__" "\n\t" \ + "sts %0,%2" "\n\t" \ + : /* no outputs */ \ + : "M" (_SFR_MEM_ADDR(_WD_CONTROL_REG)), \ + "r" (_BV(_WD_CHANGE_BIT) | _BV(WDE)), \ + "r" ((uint8_t) (((value & 0x08) ? _WD_PS3_MASK : 0x00) | \ + _BV(WDIE) | (value & 0x07)) ) \ + : "r0" \ +) +#endif + +void setupWatchdog() +{ + my_wdt_enable(WDTO_1S); +} + +//################ interrupt ################ +ISR(WDT_vect) +{ + hz_flag = true; +} diff --git a/libraries/RTCTimer/examples/sync_rtc_through_gprs/sync_rtc_through_gprs.ino b/libraries/RTCTimer/examples/sync_rtc_through_gprs/sync_rtc_through_gprs.ino new file mode 100644 index 0000000..0f82216 --- /dev/null +++ b/libraries/RTCTimer/examples/sync_rtc_through_gprs/sync_rtc_through_gprs.ino @@ -0,0 +1,99 @@ +/* + * This example shows how to synchronize the RTC with + * the help of a GPRSbee and a time service. + * + * Notice that the "epoch" of the RTC is used and the time units + * are in seconds. (The Timer library works with millis() so its + * time units are milliseconds. + */ + +//############ GPRS access details ################ +#define APN "" // Fill in your APN here + +//############ time service ################ +#define TIMEURL "http://time.sodaq.net/" + +#include +#include + +#include + +RTCTimer timer; // Instantiate the timer + +void setup() +{ + // Do the check every 24 hours + timer.every(24L * 60 * 60, syncRTCwithServer); + + // Instruct the RTCTimer how to get the current timestamp + timer.setNowCallback(getNow); +} + +void loop() +{ + timer.update(); +} + + + +/* + * Return the current timestamp + * + * This is a general purpose wrapper function to get the current timestamp. + * It can also be used for timer.setNowCallback + */ +uint32_t getNow() +{ + return rtc.now().getEpoch(); +} + + + + +/* + * Extract a number from an ASCII string + */ +bool getUValue(const char *buffer, uint32_t * value) +{ + char *eptr; + if (*buffer == '=') { + ++buffer; + } + *value = strtoul(buffer, &eptr, 0); + if (eptr != buffer) { + return true; + } + return false; +} + +//################ RTC ################ +/* + * Synchronize RTC with a time server + */ +void syncRTCwithServer(uint32_t now) +{ + char buffer[20]; + if (gprsbee.doHTTPGET(APN, TIMEURL, buffer, sizeof(buffer))) { + uint32_t newTs; + if (getUValue(buffer, &newTs)) { + // Tweak the timestamp a little because doHTTPGET took a few seconds + // to close the connection after getting the time from the server. + // The number is just a rough guess. + newTs += 3; + + uint32_t oldTs = getNow(); + int32_t diffTs = abs(newTs - oldTs); + + // Only change the RTC if the new value differs more than 3 seconds + if (diffTs > 3) { + timer.adjust(oldTs, newTs); // Update the RTCTimer administration + rtc.setEpoch(newTs); + } + return; + } + } + + // Sync failed. + // ???? Retry in, say, 3 minutes + //timer.every(5L * 60, syncRTCwithServer, 1); +} diff --git a/libraries/RTCTimer/library.properties b/libraries/RTCTimer/library.properties new file mode 100644 index 0000000..b8db16a --- /dev/null +++ b/libraries/RTCTimer/library.properties @@ -0,0 +1,11 @@ +name=RTCTimer +version=1.0.0 +author=keestux,SODAQ +maintainer=Kees Bakker +sentence=An Arduino library to easily perform scheduled tasks. +paragraph=The timing is done by looking at an RTC and an update +paragraph= function that must be called +paragraph= from the Arduino main loop. +category=Timing +url=https://github.com/SodaqMoja/RTCTimer +architectures=avr diff --git a/libraries/RTCTimer/make-zip.sh b/libraries/RTCTimer/make-zip.sh new file mode 100644 index 0000000..f6c952c --- /dev/null +++ b/libraries/RTCTimer/make-zip.sh @@ -0,0 +1,25 @@ +#!/bin/sh +# +# Make a ZIP file for distribution / publishing. + +#VERSION=$(git describe --abbrev=0 --tags 2> /dev/null) +VERSION=$(git describe --tags 2> /dev/null) +[ -z "${VERSION}" ] && { echo "ERROR: Cannot determine version. Did you do a git-tag?"; exit 1; } + +FILES=$(git ls-files|grep -v .gitignore) +[ -z "${FILES}" ] && { echo "ERROR: No files to put in ZIP."; exit 1; } + +DIRNAME="$(basename $(pwd))" +ZIPNAME="${DIRNAME}-${VERSION}" + +TDIR=/tmp/$DIRNAME +[ -d "${TDIR}" ] && { echo "ERROR: Directory '${TDIR}' exists. Please remove."; exit 1; } + +mkdir -p ${TDIR} +git ls-files | +grep -v .gitignore | +cpio -pmud ${TDIR}/ +(cd /tmp && zip -r $ZIPNAME.zip $DIRNAME) +mv /tmp/$ZIPNAME.zip . +ln -sf -T $ZIPNAME.zip ${DIRNAME}.zip +rm -fr ${TDIR} diff --git a/libraries/RTCTimer/src/RTCTimer.cpp b/libraries/RTCTimer/src/RTCTimer.cpp new file mode 100644 index 0000000..5b36e8a --- /dev/null +++ b/libraries/RTCTimer/src/RTCTimer.cpp @@ -0,0 +1,155 @@ +/* + * Copyright (c) 2014 Kees Bakker. All rights reserved. + * + * This file is part of RTCTimer. + * + * RTCTimer is free software: you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License + * as published by the Free Software Foundation, either version 3 of + * the License, or(at your option) any later version. + * + * Sodaq_dataflash is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with RTCTimer. If not, see + * . + */ + +/* + * The RTCTimer can be used to implement a simple scheduler. + * It was inspired by the Arduino Timer library by Simon Monk. + */ + +#include "RTCTimer.h" +//#include "Diag.h" + +#if 0 +RTCEvent::RTCEvent() +{ + _eventType = RTCEvent_None; + _lastEventTime = 0; + _period = 0; + _callback = 0; + _count = 0; + _repeatCount = 0; +} + +RTCTimer::RTCTimer() +{ +} +#endif + +bool RTCEvent::update(uint32_t now) +{ + bool doneEvent = false; + if ((int32_t)(now - (_lastEventTime + _period)) >= 0) { + //DIAGPRINT(F("RTCEvent::update ")); DIAGPRINTLN(_lastEventTime); + if (_lastEventTime == 0) { + // In case this wasn't initialized properly + _lastEventTime = now; + } else { + while ((int32_t)(now - (_lastEventTime + _period)) >= 0) { + // Skip all the events that are in the past + _lastEventTime += _period; + } + } + switch (_eventType) { + case RTCEvent_Every: + (*_callback)(now); + break; + default: + break; + } + if (_repeatCount > 0 && ++_count >= _repeatCount) { + // Done. Free the event. + _eventType = RTCEvent_None; + } + doneEvent = true; + } + return doneEvent; +} + +int8_t RTCTimer::every(uint32_t period, void (*callback)(uint32_t now), + int repeatCount) +{ + int8_t i = findFreeEventIndex(); + if (i == -1) + return -1; + + _events[i]._eventType = RTCEvent::RTCEvent_Every; + _events[i]._period = period; + _events[i]._repeatCount = repeatCount; + _events[i]._callback = callback; + _events[i]._lastEventTime = _now ? _now() : 0; + _events[i]._count = 0; + + return i; +} + +/* + * Reset the "last event" time of all events to the new value. + * + * This function should be called once (e.g. in setup() after creating + * all the ... + */ +void RTCTimer::resetAll(uint32_t now) +{ + for (uint8_t i = 0; i < sizeof(_events) / sizeof(_events[0]); ++i) { + if (_events[i]._eventType != RTCEvent::RTCEvent_None) { + _events[i]._lastEventTime = now; + } + } +} + +void RTCTimer::adjust(uint32_t old, uint32_t now) +{ + if (old == 0) { + resetAll(now); + return; + } + int32_t diff = now - old; + for (uint8_t i = 0; i < sizeof(_events) / sizeof(_events[0]); ++i) { + if (_events[i]._eventType != RTCEvent::RTCEvent_None) { + if (_events[i]._lastEventTime == 0) { + _events[i]._lastEventTime = now; + } else { + _events[i]._lastEventTime += diff; + } + } + } +} + +void RTCTimer::update() +{ + uint32_t now = _now ? _now() : 0; + if (now) { + update(now); + } +} + +void RTCTimer::update(uint32_t now) +{ + for (uint8_t i = 0; i < sizeof(_events) / sizeof(_events[0]); ++i) { + if (_events[i]._eventType != RTCEvent::RTCEvent_None) { + if (_events[i].update(now)) { + if (_noMultipleEvents) { + // Only one event action per update. + break; + } + } + } + } +} + +int8_t RTCTimer::findFreeEventIndex() +{ + for (uint8_t i = 0; i < sizeof(_events) / sizeof(_events[0]); ++i) { + if (_events[i]._eventType == RTCEvent::RTCEvent_None) { + return i; + } + } + return -1; +} diff --git a/libraries/RTCTimer/src/RTCTimer.h b/libraries/RTCTimer/src/RTCTimer.h new file mode 100644 index 0000000..b846c08 --- /dev/null +++ b/libraries/RTCTimer/src/RTCTimer.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2014 Kees Bakker. All rights reserved. + * + * This file is part of RTCTimer. + * + * RTCTimer is free software: you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License + * as published by the Free Software Foundation, either version 3 of + * the License, or(at your option) any later version. + * + * Sodaq_dataflash is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with RTCTimer. If not, see + * . + */ + +#include + +#ifndef RTCTIMER_H_ +#define RTCTIMER_H_ + +#define MAX_NUMBER_OF_RTCEVENTS (10) + +class RTCTimer; +class RTCEvent +{ + friend class RTCTimer; +public: + enum RTCEventType { + RTCEvent_None = 0, + RTCEvent_Every, + }; + //RTCEvent(); + + bool update(uint32_t now); + +protected: + enum RTCEventType _eventType; + uint32_t _lastEventTime; + uint32_t _period; + int _count; + int _repeatCount; + void (*_callback)(uint32_t now); +}; + +class RTCTimer +{ +public: + //RTCTimer(); + + int8_t every(uint32_t period, void (*callback)(uint32_t ts), int repeatCount=-1); + + void resetAll(uint32_t now); + void setNowCallback(uint32_t (*now)()) { _now = now; } + void adjust(uint32_t old, uint32_t now); + void update(); + void update(uint32_t now); + void allowMultipleEvents(bool allow=true) { _noMultipleEvents = !allow; } + +protected: + int8_t findFreeEventIndex(); + uint32_t (*_now)(); + RTCEvent _events[MAX_NUMBER_OF_RTCEVENTS]; + bool _noMultipleEvents; +}; + +#endif /* RTCTIMER_H_ */ diff --git a/libraries/Time/DateStrings.cpp b/libraries/Time/DateStrings.cpp new file mode 100644 index 0000000..48d55cf --- /dev/null +++ b/libraries/Time/DateStrings.cpp @@ -0,0 +1,97 @@ +/* DateStrings.cpp + * Definitions for date strings for use with the Time library + * + * Updated for Arduino 1.5.7 18 July 2014 + * + * 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 +#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 // 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 monthStr0[] PROGMEM = ""; +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"; + +const PROGMEM char * const PROGMEM monthNames_P[] = +{ + monthStr0,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"; + +const PROGMEM char * const PROGMEM dayNames_P[] = +{ + dayStr0,dayStr1,dayStr2,dayStr3,dayStr4,dayStr5,dayStr6,dayStr7 +}; + +const char 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; +} diff --git a/libraries/Time/Readme.txt b/libraries/Time/Readme.txt new file mode 100644 index 0000000..67b148e --- /dev/null +++ b/libraries/Time/Readme.txt @@ -0,0 +1,131 @@ +Readme file for Arduino Time Library + +Time is a library that provides timekeeping functionality for Arduino. + +The code is derived from the Playground DateTime library but is updated +to provide an API that is more flexable and easier to use. + +A primary goal was to enable date and time functionality that can be used with +a variety of external time sources with minimum differences required in sketch logic. + +Example sketches illustrate how similar sketch code can be used with: a Real Time Clock, +internet NTP time service, GPS time data, and Serial time messages from a computer +for time synchronization. + +The functions available in the library include: + +hour(); // the hour now (0-23) +minute(); // the minute now (0-59) +second(); // the second now (0-59) +day(); // the day now (1-31) +weekday(); // day of the week, Sunday is day 0 +month(); // the month now (1-12) +year(); // the full four digit year: (2009, 2010 etc) + +there are also functions to return the hour in 12 hour format +hourFormat12(); // the hour now in 12 hour format +isAM(); // returns true if time now is AM +isPM(); // returns true if time now is PM + +now(); // returns the current time as seconds since Jan 1 1970 + +The time and date functions can take an optional parameter for the time. This prevents +errors if the time rolls over between elements. For example, if a new minute begins +between getting the minute and second, the values will be inconsistent. Using the +following functions eliminates this probglem + 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 + + +Functions for managing the timer services are: +setTime(t); // set the system time to the give time t +setTime(hr,min,sec,day,mnth,yr); // alternative to above, yr is 2 or 4 digit yr (2010 or 10 sets year to 2010) +adjustTime(adjustment); // adjust system time by adding the adjustment value + +timeStatus(); // indicates if time has been set and recently synchronized + // returns one of the following enumerations: + timeNotSet // the time has never been set, the clock started at Jan 1 1970 + timeNeedsSync // the time had been set but a sync attempt did not succeed + timeSet // the time is set and is synced +Time and Date values are not valid if the status is timeNotSet. Otherwise values can be used but +the returned time may have drifted if the status is timeNeedsSync. + +setSyncProvider(getTimeFunction); // set the external time provider +setSyncInterval(interval); // set the number of seconds between re-sync + + +There are many convenience macros in the time.h file for time constants and conversion of time units. + +To use the library, copy the download to the Library directory. + +The Time directory contains the Time library and some example sketches +illustrating how the library can be used with various time sources: + +- TimeSerial.pde shows Arduino as a clock without external hardware. + It is synchronized by time messages sent over the serial port. + A companion Processing sketch will automatically provide these messages + if it is running and connected to the Arduino serial port. + +- TimeSerialDateStrings.pde adds day and month name strings to the sketch above + Short (3 character) and long strings are available to print the days of + the week and names of the months. + +- TimeRTC uses a DS1307 real time clock to provide time synchronization. + A basic RTC library named DS1307RTC is included in the download. + To run this sketch the DS1307RTC library must be installed. + +- TimeRTCSet is similar to the above and adds the ability to set the Real Time Clock + +- TimeRTCLog demonstrates how to calculate the difference between times. + It is a vary simple logger application that monitors events on digtial pins + and prints (to the serial port) the time of an event and the time period since the previous event. + +- TimeNTP uses the Arduino Ethernet shield to access time using the internet NTP time service. + The NTP protocol uses UDP and the UdpBytewise library is required, see: + http://bitbucket.org/bjoern/arduino_osc/src/14667490521f/libraries/Ethernet/ + +- TimeGPS gets time from a GPS + This requires the TinyGPS library from Mikal Hart: + http://arduiniana.org/libraries/TinyGPS + +Differences between this code and the playground DateTime library +although the Time library is based on the DateTime codebase, the API has changed. +Changes in the Time library API: +- time elements are functions returning int (they are variables in DateTime) +- Years start from 1970 +- days of the week and months start from 1 (they start from 0 in DateTime) +- DateStrings do not require a seperate library +- time elements can be accessed non-atomically (in DateTime they are always atomic) +- function added to automatically sync time with extrnal source +- localTime and maketime parameters changed, localTime renamed to breakTime + +Technical notes: + +Internal system time is based on the standard Unix time_t. +The value is the number of seconds since Jan 1 1970. +System time begins at zero when the sketch starts. + +The internal time can be automatically synchronized at regular intervals to an external time source. +This is enabled by calling the setSyncProvider(provider) function - the provider argument is +the address of a function that returns the current time as a time_t. +See the sketches in the examples directory for usage. + +The default interval for re-syncing the time is 5 minutes but can be changed by calling the +setSyncInterval( interval) method to set the number of seconds between re-sync attempts. + +The Time library defines a structure for holding time elements that is a compact version of the C tm structure. +All the members of the Arduino tm structure are bytes and the year is offset from 1970. +Convenience macros provide conversion to and from the Arduino format. + +Low level functions to convert between system time and individual time elements are provided: + breakTime( time, &tm); // break time_t into elements stored in tm struct + makeTime( &tm); // return time_t from elements stored in tm struct + +The DS1307RTC library included in the download provides an example of how a time provider +can use the low level functions to interface with the Time library. diff --git a/libraries/Time/Time.cpp b/libraries/Time/Time.cpp new file mode 100644 index 0000000..4cb01e7 --- /dev/null +++ b/libraries/Time/Time.cpp @@ -0,0 +1,319 @@ +/* + time.c - low level time and date functions + Copyright (c) Michael Margolis 2009-2014 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + 1.0 6 Jan 2010 - initial release + 1.1 12 Feb 2010 - fixed leap year calculation error + 1.2 1 Nov 2010 - fixed setTime bug (thanks to Korman for this) + 1.3 24 Mar 2012 - many edits by Paul Stoffregen: fixed timeStatus() to update + status, updated examples for Arduino 1.0, fixed ARM + compatibility issues, added TimeArduinoDue and TimeTeensy3 + examples, add error checking and messages to RTC examples, + add examples to DS1307RTC library. + 1.4 5 Sep 2014 - compatibility with Arduino 1.5.7 +*/ + +#if ARDUINO >= 100 +#include +#else +#include +#endif + +#include "Time.h" + +static tmElements_t tm; // a cache of time elements +static time_t cacheTime; // the time the cache was updated +static uint32_t syncInterval = 300; // time sync will be attempted after this many seconds + +void refreshCache(time_t t) { + if (t != cacheTime) { + breakTime(t, tm); + cacheTime = t; + } +} + +int hour() { // the hour now + return hour(now()); +} + +int hour(time_t t) { // the hour for the given time + refreshCache(t); + return tm.Hour; +} + +int hourFormat12() { // the hour now in 12 hour format + return hourFormat12(now()); +} + +int hourFormat12(time_t t) { // the hour for the given time in 12 hour format + refreshCache(t); + if( tm.Hour == 0 ) + return 12; // 12 midnight + else if( tm.Hour > 12) + return tm.Hour - 12 ; + else + return tm.Hour ; +} + +uint8_t isAM() { // returns true if time now is AM + return !isPM(now()); +} + +uint8_t isAM(time_t t) { // returns true if given time is AM + return !isPM(t); +} + +uint8_t isPM() { // returns true if PM + return isPM(now()); +} + +uint8_t isPM(time_t t) { // returns true if PM + return (hour(t) >= 12); +} + +int minute() { + return minute(now()); +} + +int minute(time_t t) { // the minute for the given time + refreshCache(t); + return tm.Minute; +} + +int second() { + return second(now()); +} + +int second(time_t t) { // the second for the given time + refreshCache(t); + return tm.Second; +} + +int day(){ + return(day(now())); +} + +int day(time_t t) { // the day for the given time (0-6) + refreshCache(t); + return tm.Day; +} + +int weekday() { // Sunday is day 1 + return weekday(now()); +} + +int weekday(time_t t) { + refreshCache(t); + return tm.Wday; +} + +int month(){ + return month(now()); +} + +int month(time_t t) { // the month for the given time + refreshCache(t); + return tm.Month; +} + +int year() { // as in Processing, the full four digit year: (2009, 2010 etc) + return year(now()); +} + +int year(time_t t) { // the year for the given time + refreshCache(t); + return tmYearToCalendar(tm.Year); +} + +/*============================================================================*/ +/* functions to convert to and from system time */ +/* These are for interfacing with time serivces and are not normally needed in a sketch */ + +// leap year calulator expects year argument as years offset from 1970 +#define LEAP_YEAR(Y) ( ((1970+Y)>0) && !((1970+Y)%4) && ( ((1970+Y)%100) || !((1970+Y)%400) ) ) + +static const uint8_t monthDays[]={31,28,31,30,31,30,31,31,30,31,30,31}; // API starts months from 1, this array starts from 0 + +void breakTime(time_t timeInput, tmElements_t &tm){ +// break the given time_t into time components +// this is a more compact version of the C library localtime function +// note that year is offset from 1970 !!! + + uint8_t year; + uint8_t month, monthLength; + uint32_t time; + unsigned long days; + + time = (uint32_t)timeInput; + tm.Second = time % 60; + time /= 60; // now it is minutes + tm.Minute = time % 60; + time /= 60; // now it is hours + tm.Hour = time % 24; + time /= 24; // now it is days + tm.Wday = ((time + 4) % 7) + 1; // Sunday is day 1 + + year = 0; + days = 0; + while((unsigned)(days += (LEAP_YEAR(year) ? 366 : 365)) <= time) { + year++; + } + tm.Year = year; // year is offset from 1970 + + days -= LEAP_YEAR(year) ? 366 : 365; + time -= days; // now it is days in this year, starting at 0 + + days=0; + month=0; + monthLength=0; + for (month=0; month<12; month++) { + if (month==1) { // february + if (LEAP_YEAR(year)) { + monthLength=29; + } else { + monthLength=28; + } + } else { + monthLength = monthDays[month]; + } + + if (time >= monthLength) { + time -= monthLength; + } else { + break; + } + } + tm.Month = month + 1; // jan is month 1 + tm.Day = time + 1; // day of month +} + +time_t makeTime(tmElements_t &tm){ +// assemble time elements into time_t +// note year argument is offset from 1970 (see macros in time.h to convert to other formats) +// previous version used full four digit year (or digits since 2000),i.e. 2009 was 2009 or 9 + + int i; + uint32_t seconds; + + // seconds from 1970 till 1 jan 00:00:00 of the given year + seconds= tm.Year*(SECS_PER_DAY * 365); + for (i = 0; i < tm.Year; i++) { + if (LEAP_YEAR(i)) { + seconds += SECS_PER_DAY; // add extra days for leap years + } + } + + // add days for this year, months start from 1 + for (i = 1; i < tm.Month; i++) { + if ( (i == 2) && LEAP_YEAR(tm.Year)) { + seconds += SECS_PER_DAY * 29; + } else { + seconds += SECS_PER_DAY * monthDays[i-1]; //monthDay array starts from 0 + } + } + seconds+= (tm.Day-1) * SECS_PER_DAY; + seconds+= tm.Hour * SECS_PER_HOUR; + seconds+= tm.Minute * SECS_PER_MIN; + seconds+= tm.Second; + return (time_t)seconds; +} +/*=====================================================*/ +/* Low level system time functions */ + +static uint32_t sysTime = 0; +static uint32_t prevMillis = 0; +static uint32_t nextSyncTime = 0; +static timeStatus_t Status = timeNotSet; + +getExternalTime getTimePtr; // pointer to external sync function +//setExternalTime setTimePtr; // not used in this version + +#ifdef TIME_DRIFT_INFO // define this to get drift data +time_t sysUnsyncedTime = 0; // the time sysTime unadjusted by sync +#endif + + +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 + } + if (nextSyncTime <= sysTime) { + if (getTimePtr != 0) { + time_t t = getTimePtr(); + if (t != 0) { + setTime(t); + } else { + nextSyncTime = sysTime + syncInterval; + Status = (Status == timeNotSet) ? timeNotSet : timeNeedsSync; + } + } + } + return (time_t)sysTime; +} + +void setTime(time_t t) { +#ifdef TIME_DRIFT_INFO + if(sysUnsyncedTime == 0) + sysUnsyncedTime = t; // store the time of the first call to set a valid Time +#endif + + sysTime = (uint32_t)t; + nextSyncTime = (uint32_t)t + syncInterval; + Status = timeSet; + prevMillis = millis(); // restart counting from now (thanks to Korman for this fix) +} + +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)); +} + +void adjustTime(long adjustment) { + sysTime += adjustment; +} + +// indicates if time has been set and recently synchronized +timeStatus_t timeStatus() { + now(); // required to actually update the status + return Status; +} + +void setSyncProvider( getExternalTime getTimeFunction){ + getTimePtr = getTimeFunction; + nextSyncTime = sysTime; + now(); // this will sync the clock +} + +void setSyncInterval(time_t interval){ // set the number of seconds between re-sync + syncInterval = (uint32_t)interval; + nextSyncTime = sysTime + syncInterval; +} diff --git a/libraries/Time/Time.h b/libraries/Time/Time.h new file mode 100644 index 0000000..61519f7 --- /dev/null +++ b/libraries/Time/Time.h @@ -0,0 +1,144 @@ +/* + time.h - low level time and date functions +*/ + +/* + July 3 2011 - fixed elapsedSecsThisWeek macro (thanks Vincent Valdy for this) + - fixed daysToTime_t macro (thanks maniacbug) +*/ + +#ifndef _Time_h +#ifdef __cplusplus +#define _Time_h + +#include +#ifndef __AVR__ +#include // for __time_t_defined, but avr libc lacks sys/types.h +#endif + + +#if !defined(__time_t_defined) // avoid conflict with newlib or other posix libc +typedef unsigned long time_t; +#endif + + +// This ugly hack allows us to define C++ overloaded functions, when included +// from within an extern "C", as newlib's sys/stat.h does. Actually it is +// intended to include "time.h" from the C library (on ARM, but AVR does not +// have that file at all). On Mac and Windows, the compiler will find this +// "Time.h" instead of the C library "time.h", so we may cause other weird +// and unpredictable effects by conflicting with the C library header "time.h", +// but at least this hack lets us define C++ functions as intended. Hopefully +// nothing too terrible will result from overriding the C library header?! +extern "C++" { +typedef enum {timeNotSet, timeNeedsSync, timeSet +} timeStatus_t ; + +typedef enum { + dowInvalid, dowSunday, dowMonday, dowTuesday, dowWednesday, dowThursday, dowFriday, dowSaturday +} timeDayOfWeek_t; + +typedef enum { + tmSecond, tmMinute, tmHour, tmWday, tmDay,tmMonth, tmYear, tmNbrFields +} tmByteFields; + +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; + +//convenience macros to convert to and from tm years +#define tmYearToCalendar(Y) ((Y) + 1970) // full four digit year +#define CalendarYrToTm(Y) ((Y) - 1970) +#define tmYearToY2k(Y) ((Y) - 30) // offset is from 2000 +#define y2kYearToTm(Y) ((Y) + 30) + +typedef time_t(*getExternalTime)(); +//typedef void (*setExternalTime)(const time_t); // not used in this version + + +/*==============================================================================*/ +/* Useful Constants */ +#define SECS_PER_MIN (60UL) +#define SECS_PER_HOUR (3600UL) +#define SECS_PER_DAY (SECS_PER_HOUR * 24UL) +#define DAYS_PER_WEEK (7UL) +#define SECS_PER_WEEK (SECS_PER_DAY * DAYS_PER_WEEK) +#define SECS_PER_YEAR (SECS_PER_WEEK * 52UL) +#define SECS_YR_2000 (946684800UL) // the time at the start of y2k + +/* Useful Macros for getting elapsed time */ +#define numberOfSeconds(_time_) (_time_ % SECS_PER_MIN) +#define numberOfMinutes(_time_) ((_time_ / SECS_PER_MIN) % SECS_PER_MIN) +#define numberOfHours(_time_) (( _time_% SECS_PER_DAY) / SECS_PER_HOUR) +#define dayOfWeek(_time_) ((( _time_ / SECS_PER_DAY + 4) % DAYS_PER_WEEK)+1) // 1 = Sunday +#define elapsedDays(_time_) ( _time_ / SECS_PER_DAY) // this is number of days since Jan 1 1970 +#define elapsedSecsToday(_time_) (_time_ % SECS_PER_DAY) // the number of seconds since last midnight +// The following macros are used in calculating alarms and assume the clock is set to a date later than Jan 1 1971 +// Always set the correct time before settting alarms +#define previousMidnight(_time_) (( _time_ / SECS_PER_DAY) * SECS_PER_DAY) // time at the start of the given day +#define nextMidnight(_time_) ( previousMidnight(_time_) + SECS_PER_DAY ) // time at the end of the given day +#define elapsedSecsThisWeek(_time_) (elapsedSecsToday(_time_) + ((dayOfWeek(_time_)-1) * SECS_PER_DAY) ) // note that week starts on day 1 +#define previousSunday(_time_) (_time_ - elapsedSecsThisWeek(_time_)) // time at the start of the week for the given time +#define nextSunday(_time_) ( previousSunday(_time_)+SECS_PER_WEEK) // time at the end of the week for the given time + + +/* Useful Macros for converting elapsed time to a time_t */ +#define minutesToTime_t ((M)) ( (M) * SECS_PER_MIN) +#define hoursToTime_t ((H)) ( (H) * SECS_PER_HOUR) +#define daysToTime_t ((D)) ( (D) * SECS_PER_DAY) // fixed on Jul 22 2011 +#define weeksToTime_t ((W)) ( (W) * SECS_PER_WEEK) + +/*============================================================================*/ +/* time and date functions */ +int hour(); // the hour now +int hour(time_t t); // the hour for the given time +int hourFormat12(); // the hour now in 12 hour format +int hourFormat12(time_t t); // the hour for the given time in 12 hour format +uint8_t isAM(); // returns true if time now is AM +uint8_t isAM(time_t t); // returns true the given time is AM +uint8_t isPM(); // returns true if time now is PM +uint8_t isPM(time_t t); // returns true the given time is PM +int minute(); // the minute now +int minute(time_t t); // the minute for the given time +int second(); // the second now +int second(time_t t); // the second for the given time +int day(); // the day now +int day(time_t t); // the day for the given time +int weekday(); // the weekday now (Sunday is day 1) +int weekday(time_t t); // the weekday for the given time +int month(); // the month now (Jan is month 1) +int month(time_t t); // the month for the given time +int year(); // the full four digit year: (2009, 2010 etc) +int year(time_t t); // the year for the given time + +time_t now(); // return the current time as seconds since Jan 1 1970 +void setTime(time_t t); +void setTime(int hr,int min,int sec,int day, int month, int yr); +void adjustTime(long adjustment); + +/* date strings */ +#define dt_MAX_STRING_LEN 9 // length of longest date string (excluding terminating null) +char* monthStr(uint8_t month); +char* dayStr(uint8_t day); +char* monthShortStr(uint8_t month); +char* dayShortStr(uint8_t day); + +/* time sync functions */ +timeStatus_t timeStatus(); // indicates if time has been set and recently synchronized +void setSyncProvider( getExternalTime getTimeFunction); // identify the external time provider +void setSyncInterval(time_t interval); // set the number of seconds between re-sync + +/* low level functions to convert to and from system time */ +void breakTime(time_t time, tmElements_t &tm); // break time_t into elements +time_t makeTime(tmElements_t &tm); // convert time elements into time_t + +} // extern "C++" +#endif // __cplusplus +#endif /* _Time_h */ + diff --git a/libraries/Time/examples/Processing/SyncArduinoClock/SyncArduinoClock.pde b/libraries/Time/examples/Processing/SyncArduinoClock/SyncArduinoClock.pde new file mode 100644 index 0000000..4313be3 --- /dev/null +++ b/libraries/Time/examples/Processing/SyncArduinoClock/SyncArduinoClock.pde @@ -0,0 +1,78 @@ +/** + * 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.*; +import java.util.Date; +import java.util.Calendar; +import java.util.GregorianCalendar; + +public static final short portIndex = 0; // select the com port, 0 is the first port +public static final String TIME_HEADER = "T"; //header 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); + println(getTimeNow()); +} + +void draw() +{ + textSize(20); + textAlign(CENTER); + fill(0); + text("Click to send\nTime Sync", 0, 75, 200, 175); + 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(String header, long time) { + String timeStr = String.valueOf(time); + myPort.write(header); // send header and time to arduino + myPort.write(timeStr); + myPort.write('\n'); +} + +long getTimeNow(){ + // java time is in ms, we want secs + Date d = new Date(); + Calendar cal = new GregorianCalendar(); + long current = d.getTime()/1000; + long timezone = cal.get(cal.ZONE_OFFSET)/1000; + long daylight = cal.get(cal.DST_OFFSET)/1000; + return current + timezone + daylight; +} diff --git a/libraries/Time/examples/Processing/SyncArduinoClock/readme.txt b/libraries/Time/examples/Processing/SyncArduinoClock/readme.txt new file mode 100644 index 0000000..da9721d --- /dev/null +++ b/libraries/Time/examples/Processing/SyncArduinoClock/readme.txt @@ -0,0 +1,9 @@ +SyncArduinoClock is a Processing sketch that responds to Arduino requests for +time synchronization messages. + +The portIndex must be set the Serial port connected to Arduino. + +Download TimeSerial.pde onto Arduino and you should see the time +message displayed when you run SyncArduinoClock in Processing. +The Arduino time is set from the time on your computer through the +Processing sketch. diff --git a/libraries/Time/examples/TimeArduinoDue/TimeArduinoDue.ino b/libraries/Time/examples/TimeArduinoDue/TimeArduinoDue.ino new file mode 100644 index 0000000..a19a2e0 --- /dev/null +++ b/libraries/Time/examples/TimeArduinoDue/TimeArduinoDue.ino @@ -0,0 +1,71 @@ +/* + * TimeRTC.pde + * example code illustrating Time library with Real Time Clock. + * + * This example requires Markus Lange's Arduino Due RTC Library + * https://github.com/MarkusLange/Arduino-Due-RTC-Library + */ + +#include +#include + +// Select the Slowclock source +//RTC_clock rtc_clock(RC); +RTC_clock rtc_clock(XTAL); + +void setup() { + Serial.begin(9600); + rtc_clock.init(); + if (rtc_clock.date_already_set() == 0) { + // Unfortunately, the Arduino Due hardware does not seem to + // be designed to maintain the RTC clock state when the + // board resets. Markus described it thusly: "Uhh the Due + // does reset with the NRSTB pin. This resets the full chip + // with all backup regions including RTC, RTT and SC. Only + // if the reset is done with the NRST pin will these regions + // stay with their old values." + rtc_clock.set_time(__TIME__); + rtc_clock.set_date(__DATE__); + // However, this might work on other unofficial SAM3X boards + // with different reset circuitry than Arduino Due? + } + setSyncProvider(getArduinoDueTime); + if(timeStatus()!= timeSet) + Serial.println("Unable to sync with the RTC"); + else + Serial.println("RTC has set the system time"); +} + +time_t getArduinoDueTime() +{ + return rtc_clock.unixtime(); +} + +void loop() +{ + 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); +} + diff --git a/libraries/Time/examples/TimeGPS/TimeGPS.ino b/libraries/Time/examples/TimeGPS/TimeGPS.ino new file mode 100644 index 0000000..7a0213b --- /dev/null +++ b/libraries/Time/examples/TimeGPS/TimeGPS.ino @@ -0,0 +1,87 @@ +/* + * TimeGPS.pde + * example code illustrating time synced from a GPS + * + */ + +#include +#include // http://arduiniana.org/libraries/TinyGPS/ +#include +// TinyGPS and SoftwareSerial libraries are the work of Mikal Hart + +SoftwareSerial SerialGPS = SoftwareSerial(10, 11); // receive on pin 10 +TinyGPS gps; + +// To use a hardware serial port, which is far more efficient than +// SoftwareSerial, uncomment this line and remove SoftwareSerial +//#define SerialGPS Serial1 + +// Offset hours from gps time (UTC) +const int offset = 1; // Central European Time +//const int offset = -5; // Eastern Standard Time (USA) +//const int offset = -4; // Eastern Daylight Time (USA) +//const int offset = -8; // Pacific Standard Time (USA) +//const int offset = -7; // Pacific Daylight Time (USA) + +// Ideally, it should be possible to learn the time zone +// based on the GPS position data. However, that would +// require a complex library, probably incorporating some +// sort of database using Eric Muller's time zone shape +// maps, at http://efele.net/maps/tz/ + +time_t prevDisplay = 0; // when the digital clock was displayed + +void setup() +{ + Serial.begin(9600); + while (!Serial) ; // Needed for Leonardo only + SerialGPS.begin(4800); + Serial.println("Waiting for GPS time ... "); +} + +void loop() +{ + while (SerialGPS.available()) { + if (gps.encode(SerialGPS.read())) { // process gps messages + // when TinyGPS reports new data... + unsigned long age; + int Year; + byte Month, Day, Hour, Minute, Second; + gps.crack_datetime(&Year, &Month, &Day, &Hour, &Minute, &Second, NULL, &age); + if (age < 500) { + // set the Time to the latest GPS reading + setTime(Hour, Minute, Second, Day, Month, Year); + adjustTime(offset * SECS_PER_HOUR); + } + } + } + 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 + 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); +} + diff --git a/libraries/Time/examples/TimeNTP/TimeNTP.ino b/libraries/Time/examples/TimeNTP/TimeNTP.ino new file mode 100644 index 0000000..0d3820e --- /dev/null +++ b/libraries/Time/examples/TimeNTP/TimeNTP.ino @@ -0,0 +1,135 @@ +/* + * Time_NTP.pde + * Example showing time sync to NTP time source + * + * This sketch uses the Ethernet library + */ + +#include +#include +#include +#include + +byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +// 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) + + +EthernetUDP Udp; +unsigned int localPort = 8888; // local port to listen for UDP packets + +void setup() +{ + Serial.begin(9600); + while (!Serial) ; // Needed for Leonardo only + delay(250); + Serial.println("TimeNTP Example"); + if (Ethernet.begin(mac) == 0) { + // no point in carrying on, so do nothing forevermore: + while (1) { + Serial.println("Failed to configure Ethernet using DHCP"); + delay(10000); + } + } + Serial.print("IP number assigned by DHCP is "); + Serial.println(Ethernet.localIP()); + Udp.begin(localPort); + Serial.println("waiting for sync"); + setSyncProvider(getNtpTime); +} + +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(); +} + diff --git a/libraries/Time/examples/TimeRTC/TimeRTC.pde b/libraries/Time/examples/TimeRTC/TimeRTC.pde new file mode 100644 index 0000000..42e7e7f --- /dev/null +++ b/libraries/Time/examples/TimeRTC/TimeRTC.pde @@ -0,0 +1,55 @@ +/* + * TimeRTC.pde + * example code illustrating Time library with Real Time Clock. + * + */ + +#include +#include +#include // a basic DS1307 library that returns time as a time_t + +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"); +} + +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); +} + +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); +} + diff --git a/libraries/Time/examples/TimeRTCLog/TimeRTCLog.pde b/libraries/Time/examples/TimeRTCLog/TimeRTCLog.pde new file mode 100644 index 0000000..5715eb0 --- /dev/null +++ b/libraries/Time/examples/TimeRTCLog/TimeRTCLog.pde @@ -0,0 +1,107 @@ +/* + * TimeRTCLogger.pde + * example code illustrating adding and subtracting Time. + * + * this sketch logs pin state change events + * the time of the event and time since the previous event is calculated and sent to the serial port. + */ + +#include +#include +#include // a basic DS1307 library that returns time as a time_t + +const int nbrInputPins = 6; // monitor 6 digital pins +const int inputPins[nbrInputPins] = {2,3,4,5,6,7}; // pins to monitor +boolean state[nbrInputPins] ; // the state of the monitored pins +time_t prevEventTime[nbrInputPins] ; // the time of the previous event + +void setup() { + Serial.begin(9600); + setSyncProvider(RTC.get); // the function to sync the time from the RTC + for(int i=0; i < nbrInputPins; i++){ + pinMode( inputPins[i], INPUT); + // uncomment these lines if pull-up resistors are wanted + // pinMode( inputPins[i], INPUT_PULLUP); + // state[i] = HIGH; + } +} + +void loop() +{ + for(int i=0; i < nbrInputPins; i++) + { + boolean val = digitalRead(inputPins[i]); + if(val != state[i]) + { + time_t duration = 0; // the time since the previous event + state[i] = val; + time_t timeNow = now(); + if(prevEventTime[i] > 0) + // if this was not the first state change, calculate the time from the previous change + duration = duration = timeNow - prevEventTime[i]; + logEvent(inputPins[i], val, timeNow, duration ); // log the event + prevEventTime[i] = timeNow; // store the time for this event + } + } +} + +void logEvent( int pin, boolean state, time_t timeNow, time_t duration) +{ + Serial.print("Pin "); + Serial.print(pin); + if( state == HIGH) + Serial.print(" went High at "); + else + Serial.print(" went Low at "); + showTime(timeNow); + if(duration > 0){ + // only display duration if greater than 0 + Serial.print(", Duration was "); + showDuration(duration); + } + Serial.println(); +} + + +void showTime(time_t t){ + // display the given time + Serial.print(hour(t)); + printDigits(minute(t)); + printDigits(second(t)); + Serial.print(" "); + Serial.print(day(t)); + Serial.print(" "); + Serial.print(month(t)); + Serial.print(" "); + Serial.print(year(t)); +} + +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 showDuration(time_t duration){ +// prints the duration in days, hours, minutes and seconds + if(duration >= SECS_PER_DAY){ + Serial.print(duration / SECS_PER_DAY); + Serial.print(" day(s) "); + duration = duration % SECS_PER_DAY; + } + if(duration >= SECS_PER_HOUR){ + Serial.print(duration / SECS_PER_HOUR); + Serial.print(" hour(s) "); + duration = duration % SECS_PER_HOUR; + } + if(duration >= SECS_PER_MIN){ + Serial.print(duration / SECS_PER_MIN); + Serial.print(" minute(s) "); + duration = duration % SECS_PER_MIN; + } + Serial.print(duration); + Serial.print(" second(s) "); +} + diff --git a/libraries/Time/examples/TimeRTCSet/TimeRTCSet.ino b/libraries/Time/examples/TimeRTCSet/TimeRTCSet.ino new file mode 100644 index 0000000..b4e4854 --- /dev/null +++ b/libraries/Time/examples/TimeRTCSet/TimeRTCSet.ino @@ -0,0 +1,80 @@ +/* + * TimeRTCSet.pde + * example code illustrating Time library with Real Time Clock. + * + * RTC clock is set in response to serial port time message + * A Processing example sketch to set the time is included in the download + * On Linux, you can use "date +T%s > /dev/ttyACM0" (UTC time zone) + */ + +#include +#include +#include // a basic DS1307 library that returns time as a time_t + + +void setup() { + Serial.begin(9600); + while (!Serial) ; // Needed for Leonardo only + 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"); +} + +void loop() +{ + if (Serial.available()) { + time_t t = processSyncMessage(); + if (t != 0) { + RTC.set(t); // set the RTC and the system time to the received value + setTime(t); + } + } + 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); +} + +/* code to process time sync messages from the serial port */ +#define TIME_HEADER "T" // Header tag for serial time sync message + +unsigned long processSyncMessage() { + unsigned long pctime = 0L; + const unsigned long DEFAULT_TIME = 1357041600; // Jan 1 2013 + + if(Serial.find(TIME_HEADER)) { + pctime = Serial.parseInt(); + return pctime; + if( pctime < DEFAULT_TIME) { // check the value is a valid time (greater than Jan 1 2013) + pctime = 0L; // return 0 to indicate that the time is not valid + } + } + return pctime; +} + + + + + diff --git a/libraries/Time/examples/TimeSerial/TimeSerial.ino b/libraries/Time/examples/TimeSerial/TimeSerial.ino new file mode 100644 index 0000000..426a87c --- /dev/null +++ b/libraries/Time/examples/TimeSerial/TimeSerial.ino @@ -0,0 +1,81 @@ +/* + * 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 included in the download + * On Linux, you can use "date +T%s\n > /dev/ttyACM0" (UTC time zone) + */ + +#include + +#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"); +} + +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); +} + +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 +} + diff --git a/libraries/Time/examples/TimeSerialDateStrings/TimeSerialDateStrings.ino b/libraries/Time/examples/TimeSerialDateStrings/TimeSerialDateStrings.ino new file mode 100644 index 0000000..6024776 --- /dev/null +++ b/libraries/Time/examples/TimeSerialDateStrings/TimeSerialDateStrings.ino @@ -0,0 +1,108 @@ +/* + * TimeSerialDateStrings.pde + * example code illustrating Time library date strings + * + * This sketch adds date string functionality to TimeSerial sketch + * Also shows how to handle different messages + * + * A message starting with a time header sets the time + * A Processing example sketch to automatically send the messages is inclided in the download + * On Linux, you can use "date +T%s\n > /dev/ttyACM0" (UTC time zone) + * + * A message starting with a format header sets the date format + + * send: Fs\n for short date format + * send: Fl\n for long date format + */ + +#include + +// single character message tags +#define TIME_HEADER 'T' // Header tag for serial time sync message +#define FORMAT_HEADER 'F' // Header tag indicating a date format message +#define FORMAT_SHORT 's' // short month and day strings +#define FORMAT_LONG 'l' // (lower case l) long month and day strings + +#define TIME_REQUEST 7 // ASCII bell character requests a time sync message + +static boolean isLongFormat = true; + +void setup() { + Serial.begin(9600); + while (!Serial) ; // Needed for Leonardo only + setSyncProvider( requestSync); //set function to call when sync required + Serial.println("Waiting for sync message"); +} + +void loop(){ + if (Serial.available() > 1) { // wait for at least two characters + char c = Serial.read(); + if( c == TIME_HEADER) { + processSyncMessage(); + } + else if( c== FORMAT_HEADER) { + processFormatMessage(); + } + } + if (timeStatus()!= timeNotSet) { + digitalClockDisplay(); + } + delay(1000); +} + +void digitalClockDisplay() { + // digital clock display of the time + Serial.print(hour()); + printDigits(minute()); + printDigits(second()); + Serial.print(" "); + if(isLongFormat) + Serial.print(dayStr(weekday())); + else + Serial.print(dayShortStr(weekday())); + Serial.print(" "); + Serial.print(day()); + Serial.print(" "); + if(isLongFormat) + Serial.print(monthStr(month())); + else + 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); +} + +void processFormatMessage() { + char c = Serial.read(); + if( c == FORMAT_LONG){ + isLongFormat = true; + Serial.println(F("Setting long format")); + } + else if( c == FORMAT_SHORT) { + isLongFormat = false; + Serial.println(F("Setting short format")); + } +} + +void processSyncMessage() { + unsigned long pctime; + const unsigned long DEFAULT_TIME = 1357041600; // Jan 1 2013 - paul, perhaps we define in time.h? + + 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 +} diff --git a/libraries/Time/examples/TimeTeensy3/TimeTeensy3.ino b/libraries/Time/examples/TimeTeensy3/TimeTeensy3.ino new file mode 100644 index 0000000..a06a7f9 --- /dev/null +++ b/libraries/Time/examples/TimeTeensy3/TimeTeensy3.ino @@ -0,0 +1,78 @@ +/* + * TimeRTC.pde + * example code illustrating Time library with Real Time Clock. + * + */ + +#include + +void setup() { + // set the Time library to use Teensy 3.0's RTC to keep time + setSyncProvider(getTeensy3Time); + + Serial.begin(115200); + while (!Serial); // Wait for Arduino Serial Monitor to open + delay(100); + if (timeStatus()!= timeSet) { + Serial.println("Unable to sync with the RTC"); + } else { + Serial.println("RTC has set the system time"); + } +} + +void loop() { + if (Serial.available()) { + time_t t = processSyncMessage(); + if (t != 0) { + Teensy3Clock.set(t); // set the RTC + setTime(t); + } + } + 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(); +} + +time_t getTeensy3Time() +{ + return Teensy3Clock.get(); +} + +/* code to process time sync messages from the serial port */ +#define TIME_HEADER "T" // Header tag for serial time sync message + +unsigned long processSyncMessage() { + unsigned long pctime = 0L; + const unsigned long DEFAULT_TIME = 1357041600; // Jan 1 2013 + + if(Serial.find(TIME_HEADER)) { + pctime = Serial.parseInt(); + return pctime; + if( pctime < DEFAULT_TIME) { // check the value is a valid time (greater than Jan 1 2013) + pctime = 0L; // return 0 to indicate that the time is not valid + } + } + return pctime; +} + +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); +} + diff --git a/libraries/Time/keywords.txt b/libraries/Time/keywords.txt new file mode 100644 index 0000000..85b357e --- /dev/null +++ b/libraries/Time/keywords.txt @@ -0,0 +1,33 @@ +####################################### +# Syntax Coloring Map For Time +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### +time_t KEYWORD1 +####################################### +# Methods and Functions (KEYWORD2) +####################################### +now KEYWORD2 +second KEYWORD2 +minute KEYWORD2 +hour KEYWORD2 +day KEYWORD2 +month KEYWORD2 +year KEYWORD2 +isAM KEYWORD2 +isPM KEYWORD2 +weekday KEYWORD2 +setTime KEYWORD2 +adjustTime KEYWORD2 +setSyncProvider KEYWORD2 +setSyncInterval KEYWORD2 +timeStatus KEYWORD2 +####################################### +# Instances (KEYWORD2) +####################################### + +####################################### +# Constants (LITERAL1) +####################################### diff --git a/libraries/Time/library.json b/libraries/Time/library.json new file mode 100644 index 0000000..071e74c --- /dev/null +++ b/libraries/Time/library.json @@ -0,0 +1,22 @@ +{ +"name": "Time", +"frameworks": "Arduino", +"keywords": "Time, date, hour, minute, second, day, week, month, year, RTC", +"description": "Time keeping library", +"url": "http://playground.arduino.cc/Code/Time", +"authors": +[ +{ + "name": "Michael Margolis" +}, +{ + "name": "Paul Stoffregen" +} +], +"repository": +{ + "type": "git", + "url": "https://github.com/PaulStoffregen/Time" +} +} + diff --git a/libraries/Time/library.properties b/libraries/Time/library.properties new file mode 100644 index 0000000..31b99b7 --- /dev/null +++ b/libraries/Time/library.properties @@ -0,0 +1,10 @@ +name=Time +version=1.4 +author=Michael Margolis +maintainer=Paul Stoffregen +sentence=Timekeeping functionality for Arduino +paragraph=Date and Time functions, with provisions to synchronize to external time sources like GPS and NTP (Internet). +category=Timing +url=http://playground.arduino.cc/code/time +architectures=* + diff --git a/libraries/TimeAlarms/TimeAlarms.cpp b/libraries/TimeAlarms/TimeAlarms.cpp new file mode 100644 index 0000000..f85df9a --- /dev/null +++ b/libraries/TimeAlarms/TimeAlarms.cpp @@ -0,0 +1,357 @@ +/* + TimeAlarms.cpp - Arduino Time alarms for use with Time library + Copyright (c) 208-2011 Michael Margolis. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + */ + + /* + 2 July 2011 - replaced alarm types implied from alarm value with enums to make trigger logic more robust + - this fixes bug in repeating weekly alarms - thanks to Vincent Valdy and draythomp for testing +*/ + +extern "C" { +#include // for memset +} + +#if ARDUINO > 22 +#include +#else +#include +#endif + +#include "TimeAlarms.h" +#include "Time.h" + +#define IS_ONESHOT true // constants used in arguments to create method +#define IS_REPEAT false + + +//************************************************************** +//* Alarm Class Constructor + +AlarmClass::AlarmClass() +{ + Mode.isEnabled = Mode.isOneShot = 0; + Mode.alarmType = dtNotAllocated; + value = nextTrigger = 0; + onTickHandler = NULL; // prevent a callback until this pointer is explicitly set +} + +//************************************************************** +//* Private Methods + + +void AlarmClass::updateNextTrigger() +{ + if( (value != 0) && Mode.isEnabled ) + { + time_t time = now(); + if( dtIsAlarm(Mode.alarmType) && nextTrigger <= time ) // update alarm if next trigger is not yet in the future + { + if(Mode.alarmType == dtExplicitAlarm ) // is the value a specific date and time in the future + { + nextTrigger = value; // yes, trigger on this value + } + else if(Mode.alarmType == dtDailyAlarm) //if this is a daily alarm + { + if( value + previousMidnight(now()) <= time) + { + nextTrigger = value + nextMidnight(time); // if time has passed then set for tomorrow + } + else + { + nextTrigger = value + previousMidnight(time); // set the date to today and add the time given in value + } + } + else if(Mode.alarmType == dtWeeklyAlarm) // if this is a weekly alarm + { + if( (value + previousSunday(now())) <= time) + { + nextTrigger = value + nextSunday(time); // if day has passed then set for the next week. + } + else + { + nextTrigger = value + previousSunday(time); // set the date to this week today and add the time given in value + } + } + else // its not a recognized alarm type - this should not happen + { + Mode.isEnabled = 0; // Disable the alarm + } + } + if( Mode.alarmType == dtTimer) + { + // its a timer + nextTrigger = time + value; // add the value to previous time (this ensures delay always at least Value seconds) + } + } + else + { + Mode.isEnabled = 0; // Disable if the value is 0 + } +} + +//************************************************************** +//* Time Alarms Public Methods + +TimeAlarmsClass::TimeAlarmsClass() +{ + isServicing = false; + for(uint8_t id = 0; id < dtNBR_ALARMS; id++) + free(id); // ensure all Alarms are cleared and available for allocation +} + +// this method creates a trigger at the given absolute time_t +// it replaces the call to alarmOnce with values greater than a week +AlarmID_t TimeAlarmsClass::triggerOnce(time_t value, OnTick_t onTickHandler){ // trigger once at the given time_t + if( value > 0) + return create( value, onTickHandler, IS_ONESHOT, dtExplicitAlarm ); + else + return dtINVALID_ALARM_ID; // dont't allocate if the time is greater than one day +} + +// this method will now return an error if the value is greater than one day - use DOW methods for weekly alarms +AlarmID_t TimeAlarmsClass::alarmOnce(time_t value, OnTick_t onTickHandler){ // trigger once at the given time of day + if( value <= SECS_PER_DAY) + return create( value, onTickHandler, IS_ONESHOT, dtDailyAlarm ); + else + return dtINVALID_ALARM_ID; // dont't allocate if the time is greater than one day +} + +AlarmID_t TimeAlarmsClass::alarmOnce(const int H, const int M, const int S,OnTick_t onTickHandler){ // as above with HMS arguments + return create( AlarmHMS(H,M,S), onTickHandler, IS_ONESHOT, dtDailyAlarm ); +} + +AlarmID_t TimeAlarmsClass::alarmOnce(const timeDayOfWeek_t DOW, const int H, const int M, const int S, OnTick_t onTickHandler){ // as above, with day of week + return create( (DOW-1) * SECS_PER_DAY + AlarmHMS(H,M,S), onTickHandler, IS_ONESHOT, dtWeeklyAlarm ); +} + +// this method will now return an error if the value is greater than one day - use DOW methods for weekly alarms +AlarmID_t TimeAlarmsClass::alarmRepeat(time_t value, OnTick_t onTickHandler){ // trigger daily at the given time + if( value <= SECS_PER_DAY) + return create( value, onTickHandler, IS_REPEAT, dtDailyAlarm ); + else + return dtINVALID_ALARM_ID; // dont't allocate if the time is greater than one day + } + + AlarmID_t TimeAlarmsClass::alarmRepeat(const int H, const int M, const int S, OnTick_t onTickHandler){ // as above with HMS arguments + return create( AlarmHMS(H,M,S), onTickHandler, IS_REPEAT, dtDailyAlarm ); + } + + AlarmID_t TimeAlarmsClass::alarmRepeat(const timeDayOfWeek_t DOW, const int H, const int M, const int S, OnTick_t onTickHandler){ // as above, with day of week + return create( (DOW-1) * SECS_PER_DAY + AlarmHMS(H,M,S), onTickHandler, IS_REPEAT, dtWeeklyAlarm ); + } + + AlarmID_t TimeAlarmsClass::timerOnce(time_t value, OnTick_t onTickHandler){ // trigger once after the given number of seconds + return create( value, onTickHandler, IS_ONESHOT, dtTimer ); + } + + AlarmID_t TimeAlarmsClass::timerOnce(const int H, const int M, const int S, OnTick_t onTickHandler){ // As above with HMS arguments + return create( AlarmHMS(H,M,S), onTickHandler, IS_ONESHOT, dtTimer ); + } + + AlarmID_t TimeAlarmsClass::timerRepeat(time_t value, OnTick_t onTickHandler){ // trigger after the given number of seconds continuously + return create( value, onTickHandler, IS_REPEAT, dtTimer); + } + + AlarmID_t TimeAlarmsClass::timerRepeat(const int H, const int M, const int S, OnTick_t onTickHandler){ // trigger after the given number of seconds continuously + return create( AlarmHMS(H,M,S), onTickHandler, IS_REPEAT, dtTimer); + } + + void TimeAlarmsClass::enable(AlarmID_t ID) + { + if(isAllocated(ID)) { + Alarm[ID].Mode.isEnabled = (Alarm[ID].value != 0) && (Alarm[ID].onTickHandler != 0) ; // only enable if value is non zero and a tick handler has been set + Alarm[ID].updateNextTrigger(); // trigger is updated whenever this is called, even if already enabled + } + } + + void TimeAlarmsClass::disable(AlarmID_t ID) + { + if(isAllocated(ID)) + Alarm[ID].Mode.isEnabled = false; + } + + // 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 + } + } + + // return the value for the given alarm ID + time_t TimeAlarmsClass::read(AlarmID_t ID) + { + if(isAllocated(ID)) + return Alarm[ID].value ; + else + return dtINVALID_TIME; + } + + // return the alarm type for the given alarm ID + dtAlarmPeriod_t TimeAlarmsClass::readType(AlarmID_t ID) + { + if(isAllocated(ID)) + return (dtAlarmPeriod_t)Alarm[ID].Mode.alarmType ; + else + return dtNotAllocated; + } + + void TimeAlarmsClass::free(AlarmID_t ID) + { + if(isAllocated(ID)) + { + Alarm[ID].Mode.isEnabled = false; + Alarm[ID].Mode.alarmType = dtNotAllocated; + Alarm[ID].onTickHandler = 0; + Alarm[ID].value = 0; + Alarm[ID].nextTrigger = 0; + } + } + + // returns the number of allocated timers + uint8_t TimeAlarmsClass::count() + { + uint8_t c = 0; + for(uint8_t id = 0; id < dtNBR_ALARMS; id++) + { + if(isAllocated(id)) + c++; + } + return c; + } + + // returns true only if id is allocated and the type is a time based alarm, returns false if not allocated or if its a timer + bool TimeAlarmsClass::isAlarm(AlarmID_t ID) + { + return( isAllocated(ID) && dtIsAlarm(Alarm[ID].Mode.alarmType) ); + } + + // returns true if this id is allocated + bool TimeAlarmsClass::isAllocated(AlarmID_t ID) + { + return( ID < dtNBR_ALARMS && Alarm[ID].Mode.alarmType != dtNotAllocated ); + } + + + AlarmID_t TimeAlarmsClass::getTriggeredAlarmId() //returns the currently triggered alarm id + // returns dtINVALID_ALARM_ID if not invoked from within an alarm handler + { + if(isServicing) + return servicedAlarmId; // new private data member used instead of local loop variable i in serviceAlarms(); + else + return dtINVALID_ALARM_ID; // valid ids only available when servicing a callback + } + + // following functions are not Alarm ID specific. + void TimeAlarmsClass::delay(unsigned long ms) + { + unsigned long start = millis(); + while( millis() - start <= ms) + serviceAlarms(); + } + + void TimeAlarmsClass::waitForDigits( uint8_t Digits, dtUnits_t Units) + { + while(Digits != getDigitsNow(Units) ) + { + serviceAlarms(); + } + } + + void TimeAlarmsClass::waitForRollover( dtUnits_t Units) + { + while(getDigitsNow(Units) == 0 ) // if its just rolled over than wait for another rollover + serviceAlarms(); + waitForDigits(0, Units); + } + + uint8_t TimeAlarmsClass::getDigitsNow( dtUnits_t Units) + { + time_t time = now(); + if(Units == dtSecond) return numberOfSeconds(time); + if(Units == dtMinute) return numberOfMinutes(time); + if(Units == dtHour) return numberOfHours(time); + if(Units == dtDay) return dayOfWeek(time); + return 255; // This should never happen + } + + //*********************************************************** + //* Private Methods + + void TimeAlarmsClass::serviceAlarms() + { + if(! isServicing) + { + isServicing = true; + for( servicedAlarmId = 0; servicedAlarmId < dtNBR_ALARMS; servicedAlarmId++) + { + if( Alarm[servicedAlarmId].Mode.isEnabled && (now() >= Alarm[servicedAlarmId].nextTrigger) ) + { + OnTick_t TickHandler = Alarm[servicedAlarmId].onTickHandler; + if(Alarm[servicedAlarmId].Mode.isOneShot) + free(servicedAlarmId); // free the ID if mode is OnShot + else + Alarm[servicedAlarmId].updateNextTrigger(); + if( TickHandler != NULL) { + (*TickHandler)(); // call the handler + } + } + } + isServicing = false; + } + } + + // 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; + } + + // attempt to create an alarm and return true if successful + AlarmID_t TimeAlarmsClass::create( time_t value, OnTick_t onTickHandler, uint8_t isOneShot, dtAlarmPeriod_t alarmType, uint8_t isEnabled) + { + if( ! (dtIsAlarm(alarmType) && now() < SECS_PER_YEAR)) // only create alarm ids if the time is at least Jan 1 1971 + { + for(uint8_t id = 0; id < dtNBR_ALARMS; id++) + { + if( Alarm[id].Mode.alarmType == dtNotAllocated ) + { + // here if there is an Alarm id that is not allocated + Alarm[id].onTickHandler = onTickHandler; + Alarm[id].Mode.isOneShot = isOneShot; + Alarm[id].Mode.alarmType = alarmType; + Alarm[id].value = value; + isEnabled ? enable(id) : disable(id); + return id; // alarm created ok + } + } + } + return dtINVALID_ALARM_ID; // no IDs available or time is invalid + } + + // make one instance for the user to use + TimeAlarmsClass Alarm = TimeAlarmsClass() ; + diff --git a/libraries/TimeAlarms/TimeAlarms.h b/libraries/TimeAlarms/TimeAlarms.h new file mode 100644 index 0000000..840ba0b --- /dev/null +++ b/libraries/TimeAlarms/TimeAlarms.h @@ -0,0 +1,127 @@ +// TimeAlarms.h - Arduino Time alarms header for use with Time library + +#ifndef TimeAlarms_h +#define TimeAlarms_h + +#include + +#include "Time.h" + +#define dtNBR_ALARMS 6 // max is 255 + +#define USE_SPECIALIST_METHODS // define this for testing + +typedef enum { dtMillisecond, dtSecond, dtMinute, dtHour, dtDay } dtUnits_t; + +typedef struct { + uint8_t alarmType :4 ; // enumeration of daily/weekly (in future: biweekly/semimonthly/monthly/annual) + // note that the current API only supports daily or weekly alarm periods + uint8_t isEnabled :1 ; // the timer is only actioned if isEnabled is true + uint8_t isOneShot :1 ; // the timer will be de-allocated after trigger is processed + } + AlarmMode_t ; + +// new time based alarms should be added just before dtLastAlarmType +typedef enum {dtNotAllocated, dtTimer, dtExplicitAlarm, dtDailyAlarm, dtWeeklyAlarm, dtLastAlarmType } dtAlarmPeriod_t ; // in future: dtBiweekly, dtMonthly, dtAnnual + +// macro to return true if the given type is a time based alarm, false if timer or not allocated +#define dtIsAlarm(_type_) (_type_ >= dtExplicitAlarm && _type_ < dtLastAlarmType) + +typedef uint8_t AlarmID_t; +typedef AlarmID_t AlarmId; // Arduino friendly name + +#define dtINVALID_ALARM_ID 255 +#define dtINVALID_TIME 0L + +class AlarmClass; // forward reference +typedef void (*OnTick_t)(); // alarm callback function typedef + +// class defining an alarm instance, only used by dtAlarmsClass +class AlarmClass +{ +private: + +public: + AlarmClass(); + OnTick_t onTickHandler; + void updateNextTrigger(); + time_t value; + time_t nextTrigger; + AlarmMode_t Mode; +}; + +// class containing the collection of alarms +class TimeAlarmsClass +{ +private: + AlarmClass Alarm[dtNBR_ALARMS]; + void serviceAlarms(); + uint8_t isServicing; + uint8_t servicedAlarmId; // the alarm currently being serviced + AlarmID_t create( time_t value, OnTick_t onTickHandler, uint8_t isOneShot, dtAlarmPeriod_t alarmType, uint8_t isEnabled=true); + +public: + TimeAlarmsClass(); + // functions to create alarms and timers + + AlarmID_t triggerOnce(time_t value, OnTick_t onTickHandler); // trigger once at the given time_t + + AlarmID_t alarmRepeat(time_t value, OnTick_t onTickHandler); // trigger daily at given time of day + AlarmID_t alarmRepeat(const int H, const int M, const int S, OnTick_t onTickHandler); // as above, with hms arguments + AlarmID_t alarmRepeat(const timeDayOfWeek_t DOW, const int H, const int M, const int S, OnTick_t onTickHandler); // as above, with day of week + + AlarmID_t alarmOnce(time_t value, OnTick_t onTickHandler); // trigger once at given time of day + AlarmID_t alarmOnce( const int H, const int M, const int S, OnTick_t onTickHandler); // as above, with hms arguments + AlarmID_t alarmOnce(const timeDayOfWeek_t DOW, const int H, const int M, const int S, OnTick_t onTickHandler); // as above, with day of week + + AlarmID_t timerOnce(time_t value, OnTick_t onTickHandler); // trigger once after the given number of seconds + AlarmID_t timerOnce(const int H, const int M, const int S, OnTick_t onTickHandler); // As above with HMS arguments + + AlarmID_t timerRepeat(time_t value, OnTick_t onTickHandler); // trigger after the given number of seconds continuously + AlarmID_t timerRepeat(const int H, const int M, const int S, OnTick_t onTickHandler); // As above with HMS arguments + + void delay(unsigned long ms); + + // utility methods + uint8_t getDigitsNow( dtUnits_t Units); // returns the current digit value for the given time unit + void waitForDigits( uint8_t Digits, dtUnits_t Units); + void waitForRollover(dtUnits_t Units); + + // low level methods + void enable(AlarmID_t ID); // enable the alarm to trigger + void disable(AlarmID_t ID); // prevent the alarm from triggering + AlarmID_t getTriggeredAlarmId(); // returns the currently triggered alarm id + void write(AlarmID_t ID, time_t value); // write the value (and enable) the alarm with the given ID + time_t read(AlarmID_t ID); // return the value for the given timer + dtAlarmPeriod_t readType(AlarmID_t ID); // return the alarm type for the given alarm ID + +#ifndef USE_SPECIALIST_METHODS +private: // the following methods are for testing and are not documented as part of the standard library +#endif + void free(AlarmID_t ID); // free the id to allow its reuse + uint8_t count(); // returns the number of allocated timers + time_t getNextTrigger(); // returns the time of the next scheduled alarm + bool isAllocated(AlarmID_t ID); // returns true if this id is allocated + bool isAlarm(AlarmID_t ID); // returns true if id is for a time based alarm, false if its a timer or not allocated +}; + +extern TimeAlarmsClass Alarm; // make an instance for the user + +/*============================================================================== + * MACROS + *============================================================================*/ + +/* public */ +#define waitUntilThisSecond(_val_) waitForDigits( _val_, dtSecond) +#define waitUntilThisMinute(_val_) waitForDigits( _val_, dtMinute) +#define waitUntilThisHour(_val_) waitForDigits( _val_, dtHour) +#define waitUntilThisDay(_val_) waitForDigits( _val_, dtDay) +#define waitMinuteRollover() waitForRollover(dtSecond) +#define waitHourRollover() waitForRollover(dtMinute) +#define waitDayRollover() waitForRollover(dtHour) + +#define AlarmHMS(_hr_, _min_, _sec_) (_hr_ * SECS_PER_HOUR + _min_ * SECS_PER_MIN + _sec_) + + +#endif /* TimeAlarms_h */ + diff --git a/libraries/TimeAlarms/examples/TimeAlarmExample/TimeAlarmExample.pde b/libraries/TimeAlarms/examples/TimeAlarmExample/TimeAlarmExample.pde new file mode 100644 index 0000000..cb5729b --- /dev/null +++ b/libraries/TimeAlarms/examples/TimeAlarmExample/TimeAlarmExample.pde @@ -0,0 +1,77 @@ +/* + * TimeAlarmExample.pde + * + * This example calls alarm functions at 8:30 am and at 5:45 pm (17:45) + * and simulates turning lights on at night and off in the morning + * A weekly timer is set for Saturdays at 8:30:30 + * + * A timer is called every 15 seconds + * Another timer is called once only after 10 seconds + * + * At startup the time is set to Jan 1 2011 8:29 am + */ + +#include +#include + +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); +} + diff --git a/libraries/TimeAlarms/keywords.txt b/libraries/TimeAlarms/keywords.txt new file mode 100644 index 0000000..8bc9f79 --- /dev/null +++ b/libraries/TimeAlarms/keywords.txt @@ -0,0 +1,25 @@ +####################################### +# Syntax Coloring Map For TimeAlarms +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +####################################### +# Methods and Functions (KEYWORD2) +####################################### +alarmRepeat KEYWORD2 +alarmOnce KEYWORD2 +timerRepeat KEYWORD2 +timerOnce KEYWORD2 +delay KEYWORD2 +####################################### +# Instances (KEYWORD2) +####################################### +Alarm KEYWORD2 +####################################### +# Constants (LITERAL1) +####################################### +dtINVALID_ALARM_ID LITERAL1 +dtINVALID_TIME LITERAL1 diff --git a/libraries/TimeAlarms/library.json b/libraries/TimeAlarms/library.json new file mode 100644 index 0000000..7c32272 --- /dev/null +++ b/libraries/TimeAlarms/library.json @@ -0,0 +1,16 @@ +{ +"name": "TimeAlarms", +"frameworks": "Arduino", +"keywords": "Time, alarm, schedule, date, hour, minute, second, day, week, month, year", +"description": "Schedule alarms to occur at specific times", +"url": "http://playground.arduino.cc/Code/Time", +"authors": +{ + "name": "Michael Margolis" +}, +"repository": +{ + "type": "git", + "url": "https://github.com/PaulStoffregen/TimeAlarms" +} +} diff --git a/libraries/TimeAlarms/library.properties b/libraries/TimeAlarms/library.properties new file mode 100644 index 0000000..98dc05f --- /dev/null +++ b/libraries/TimeAlarms/library.properties @@ -0,0 +1,10 @@ +name=TimeAlarms +version=1.4 +author=Michael Margolis +maintainer=Paul Stoffregen +sentence=Perform tasks at specific times or after specific intervals. +paragraph=The Alarm library is a companion to the Time library that makes it easy to perform tasks at specific times or after specific intervals. Tasks scheduled at a particular time of day are called Alarms, tasks scheduled after an interval of time has elapsed are called Timers. These tasks can be created to continuously repeat or to occur once only. +category=Timing +url=http://playground.arduino.cc/code/time +architectures=* + diff --git a/libraries/TimeAlarms/readme.txt b/libraries/TimeAlarms/readme.txt new file mode 100644 index 0000000..4cdaa5b --- /dev/null +++ b/libraries/TimeAlarms/readme.txt @@ -0,0 +1,220 @@ +Alarms + +The Alarm library is a companion to the Time library that makes it easy to +perform tasks at specific times or after specific intervals. + +Tasks scheduled at a particular time of day are called Alarms, +tasks scheduled after an interval of time has elapsed are called Timers. +These tasks can be created to continuously repeat or to occur once only. + +Here is how you create an alarm to trigger a task repeatedly at a particular time of day: + Alarm.alarmRepeat(8,30,0, MorningAlarm); +This would call the function MorningAlarm() at 8:30 am every day. + +If you want the alarm to trigger only once you can use the alarmOnce method: + Alarm.alarmOnce(8,30,0, MorningAlarm); +This calls a MorningAlarm() function in a sketch once only (when the time is next 8:30am) + +Alarms can be specified to trigger a task repeatedly at a particular day of week and time of day: + Alarm.alarmRepeat(dowMonday, 9,15,0, MondayMorningAlarm); +This would call the function WeeklyAlarm() at 9:15am every Monday. + +If you want the alarm to trigger once only on a particular day and time you can do this: + Alarm.alarmOnce(dowMonday, 9,15,0, MondayMorningAlarm); +This would call the function MondayMorning() Alarm on the next Monday at 9:15am. + +Timers trigger tasks that occur after a specified interval of time has passed. +The timer interval can be specified in seconds, or in hour, minutes and seconds. + Alarm.timerRepeat(15, Repeats); // timer task every 15 seconds +This calls the Repeats() function in your sketch every 15 seconds. + +If you want a timer to trigger once only, you can use the timerOnce method: + Alarm.timerOnce(10, OnceOnly); // called once after 10 seconds +This calls the onceOnly() function in a sketch 10 seconds after the timer is created. + +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) + +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). + + + +Here is an example sketch: + +This sketch triggers daily alarms at 8:30 am and 17:45 pm. +A Timer is triggered every 15 seconds, another timer triggers once only after 10 seconds. +A weekly alarm is triggered every Sunday at 8:30:30 + +#include +#include + +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); +} +Note that the loop code calls Alarm.delay(1000) - Alarm.delay must be used +instead of the usual arduino delay function because the alarms are serviced in the Alarm.delay method. +Failing to regularly call Alarm.delay will result in the alarms not being triggered +so always use Alarm.delay instead of delay in sketches that use the Alarms library. + +Functional reference: + +// functions to create alarms and timers + +Alarm.triggerOnce(value, AlarmFunction); + Description: Call user provided AlarmFunction once at the date and time of the given value + See the Ttime library for more on time_t values + +Alarm.alarmRepeat(Hour, Minute, Second, AlarmFunction); + Description: Calls user provided AlarmFunction every day at the given Hour, Minute and Second. + +Alarm.alarmRepeat(value, AlarmFunction); + Description: Calls user provided AlarmFunction every day at the time indicated by the given value + +Alarm.alarmRepeat(DayOfWeek, Hour, Minute, Second, AlarmFunction); + Description: Calls user provided AlarmFunction every week on the given DayOfWeek, Hour, Minute and Second. + +Alarm.alarmOnce(Hour, Minute, Second, AlarmFunction); + Description: Calls user provided AlarmFunction once when the Arduino time next reaches the given Hour, Minute and Second. + +Alarm.alarmOnce(value, AlarmFunction); + Description: Calls user provided AlarmFunction once at the next time indicated by the given value + +Alarm.alarmOnce(DayOfWeek, Hour, Minute, Second, AlarmFunction); + Description: Calls user provided AlarmFunction once only on the next DayOfWeek, Hour, Minute and Second. + +Alarm.timerRepeat(Period, TimerFunction); + Description: Continuously calls user provided TimerFunction after the given period in seconds has elapsed. + +Alarm.timerRepeat(Hour, Minute, Second, TimerFunction); + Description: As timerRepeat above, but period is the number of seconds in the given Hour, Minute and Second parameters + +Alarm.timerOnce(Period, TimerFunction); + Description: Calls user provided TimerFunction once only after the given period in seconds has elapsed. + +Alarm.timerOnce(Hour, Minute, Second, TimerFunction); + Description: As timerOnce above, but period is the number of seconds in the given Hour, Minute and Second parameters + +Alarm.delay( period) + Description: Similar to Arduino delay - pauses the program for the period (in miliseconds) specified. + Call this function rather than the Arduino delay function when using the Alarms library. + The timeliness of the triggers depends on sketch delays using this function. + +Low level functions not usually required for typical applications: + disable( ID); - prevent the alarm associated with the given ID from triggering + enable(ID); - enable the alarm + write(ID, value); - write the value (and enable) the alarm for the given ID + read(ID); - return the value for the given ID + readType(ID); - return the alarm type for the given alarm ID + getTriggeredAlarmId(); - returns the currently triggered alarm id, only valid in an alarm callback + +FAQ + +Q: What hardware and software is needed to use this library? +A: This library requires the Time library. No internal or external hardware is used by the Alarm library. + +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. + +Q: Are there any restrictions on the code in a task handler function? +A: No. The scheduler does not use interrupts so your task handling function is no +different from other functions you create in your sketch. + +Q: What are the shortest and longest intervals that can be scheduled? +A: Time intervals can range from 1 second to years. +(If you need timer intervals shorter than 1 second then the TimedAction library +by Alexander Brevig may be more suitable, see: http://www.arduino.cc/playground/Code/TimedAction) + +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. + +Q: What is the valid range of times supported by these libraries? +A: The time library is intended to handle times from Jan 1 1970 through Jan 19 2038. + The Alarms library expects dates to be on or after Jan1 1971 so clocks should no be set earlier than this if using Alarms. +(The functions to create alarms will return an error if an earlier date is given). + +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 +} +