티스토리 뷰
Time.h
아두이노 playground에 Time.h 헤더파일이 있다.
날짜 및 시간 기능, GPS 및 NTP(인터넷)과 같은 외부 시간 소스와 동기화 하는 기능.
이 라이브러리는 종종 TimeAlarms 및 DS1307RTC와 함께 사용된다.
(https://www.arduinolibraries.info/libraries/time)
Time-1.5.0.zip 파일을 다운받으면 Time.h와 TimeLib.h 두개의 헤더파일이 있다.
Time.h 헤더파일에서 TimeLib.h 헤더파일을 include 한 것을 확인할 수 있다.
Time 라이브러리를 사용하면 날짜와 시간을 추적할 수 있다.
많은 아두이노 보드에서는 시간 측정을 위해 수정 결정판을 사용하고 있으며. 이 경우 오차는 하루에 2초 정도다.
배터리가 없기 때문에 전원 차단 시간을 기억하지 못한다.
따라서 스케치를 시작할 때마다 시간이 0부터 다시 시작되므로 setTime 함수를 사용해서 시간을 설정해야 한다.
// Time.h
#include "TimeLib.h"
/*
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 <inttypes.h>
#ifndef __AVR__
#include <sys/types.h> // 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 */
Timealarms.h
알람 라이브러리는 특정 시간 또는 특정 간격 후에 작업을 쉽게 수행할 수 있는 시간 라이브러리의 동반자입니다.
특정 시간에 예약 된 작업을 알람이라고 하고, 일정 시간이 지난 후에 예약된 작업을 타이머라고 합니다.
이러한 작업은 지속적으로 반복하거나 한번만 발생하도록 만들 수 있습니다.
TimeAlarms 라이브러리를 사용하려면 Time 라이브러리를 설치해야 한다.
(https://www.arduinolibraries.info/libraries/time-alarms)
// TimeAlarms.h - Arduino Time alarms header for use with Time library
#ifndef TimeAlarms_h
#define TimeAlarms_h
#include <Arduino.h>
#include "TimeLib.h"
#if defined(__AVR__)
#define dtNBR_ALARMS 6 // max is 255
#else
#define dtNBR_ALARMS 12 // assume non-AVR has more memory
#endif
#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)
#define dtUseAbsoluteValue(_type_) (_type_ == dtTimer || _type_ == dtExplicitAlarm)
typedef uint8_t AlarmID_t;
typedef AlarmID_t AlarmId; // Arduino friendly name
#define dtINVALID_ALARM_ID 255
#define dtINVALID_TIME (time_t)(-1)
#define AlarmHMS(_hr_, _min_, _sec_) (_hr_ * SECS_PER_HOUR + _min_ * SECS_PER_MIN + _sec_)
typedef void (*OnTick_t)(); // alarm callback function typedef
// class defining an alarm instance, only used by dtAlarmsClass
class AlarmClass
{
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);
public:
TimeAlarmsClass();
// functions to create alarms and timers
// trigger once at the given time in the future
AlarmID_t triggerOnce(time_t value, OnTick_t onTickHandler) {
if (value <= 0) return dtINVALID_ALARM_ID;
return create(value, onTickHandler, true, dtExplicitAlarm);
}
// trigger once at given time of day
AlarmID_t alarmOnce(time_t value, OnTick_t onTickHandler) {
if (value <= 0 || value > SECS_PER_DAY) return dtINVALID_ALARM_ID;
return create(value, onTickHandler, true, dtDailyAlarm);
}
AlarmID_t alarmOnce(const int H, const int M, const int S, OnTick_t onTickHandler) {
return alarmOnce(AlarmHMS(H,M,S), onTickHandler);
}
// trigger once on a given day and time
AlarmID_t alarmOnce(const timeDayOfWeek_t DOW, const int H, const int M, const int S, OnTick_t onTickHandler) {
time_t value = (DOW-1) * SECS_PER_DAY + AlarmHMS(H,M,S);
if (value <= 0) return dtINVALID_ALARM_ID;
return create(value, onTickHandler, true, dtWeeklyAlarm);
}
// trigger daily at given time of day
AlarmID_t alarmRepeat(time_t value, OnTick_t onTickHandler) {
if (value > SECS_PER_DAY) return dtINVALID_ALARM_ID;
return create(value, onTickHandler, false, dtDailyAlarm);
}
AlarmID_t alarmRepeat(const int H, const int M, const int S, OnTick_t onTickHandler) {
return alarmRepeat(AlarmHMS(H,M,S), onTickHandler);
}
// trigger weekly at a specific day and time
AlarmID_t alarmRepeat(const timeDayOfWeek_t DOW, const int H, const int M, const int S, OnTick_t onTickHandler) {
time_t value = (DOW-1) * SECS_PER_DAY + AlarmHMS(H,M,S);
if (value <= 0) return dtINVALID_ALARM_ID;
return create(value, onTickHandler, false, dtWeeklyAlarm);
}
// trigger once after the given number of seconds
AlarmID_t timerOnce(time_t value, OnTick_t onTickHandler) {
if (value <= 0) return dtINVALID_ALARM_ID;
return create(value, onTickHandler, true, dtTimer);
}
AlarmID_t timerOnce(const int H, const int M, const int S, OnTick_t onTickHandler) {
return timerOnce(AlarmHMS(H,M,S), onTickHandler);
}
// trigger at a regular interval
AlarmID_t timerRepeat(time_t value, OnTick_t onTickHandler) {
if (value <= 0) return dtINVALID_ALARM_ID;
return create(value, onTickHandler, false, dtTimer);
}
AlarmID_t timerRepeat(const int H, const int M, const int S, OnTick_t onTickHandler) {
return timerRepeat(AlarmHMS(H,M,S), onTickHandler);
}
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
bool getIsServicing(); // returns isServicing
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
void free(AlarmID_t ID); // free the id to allow its reuse
#ifndef USE_SPECIALIST_METHODS
private: // the following methods are for testing and are not documented as part of the standard library
#endif
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)
#endif /* TimeAlarms_h */
RTC.h
실시간 클럭 사용하기
실시간 클럭(RTC)에서 제공하는 시간을 사용하고 싶다.
일반적으로 외장 보드에는 배터리 백업이 있기 때문에 아두이노를 다시 설정하거나 끄더라도 시간이 올바르게 유지된다.
RTC를 사용하는 가장 간단한 방법은 Time 라이브러리의 부속 라이브러리인 DS1307RTC.h를 사용하는 것이다.
RTC.adjust를 사용하면 시간을 설정할 수 있다.
DateTime 라이브러리는 시간 관리 기능을 추가하고 년, 월, 일을 사용하여 초기화한다. (시, 분, 초까지 초기화 가능)
예제는 기본 시간으로 약간 수정되었으므로 시간을 설정하기 위해 별도의 프로그램이 없어도 실행된다.
TimeSpan은 특정 시간이 아니라 '며칠, 몇시간, 몇분, 몇초'와 같은 시간의 크기를 나타내며 DateTime과 함께 사용한다.
TimeSpan Span = TimeSpan(0, 9, 0, 0)
Current = Current + Span ▶ Current 시간이 GMT에서 한국은 9hr 더해야 하기 때문에 Current + Span으로 계산한다.
/**************************************************************************/
/*!
@file RTClib.h
Original library by JeeLabs http://news.jeelabs.org/code/, released to the public domain
License: MIT (see LICENSE)
This is a fork of JeeLab's fantastic real time clock library for Arduino.
For details on using this library with an RTC module like the DS1307, PCF8523, or DS3231,
see the guide at: https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/overview
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
*/
/**************************************************************************/
#ifndef _RTCLIB_H_
#define _RTCLIB_H_
#include <Arduino.h>
class TimeSpan;
/** Registers */
#define PCF8523_ADDRESS 0x68 ///< I2C address for PCF8523
#define PCF8523_CLKOUTCONTROL 0x0F ///< Timer and CLKOUT control register
#define PCF8523_CONTROL_3 0x02 ///< Control and status register 3
#define PCF8523_OFFSET 0x0E ///< Offset register
#define DS1307_ADDRESS 0x68 ///< I2C address for DS1307
#define DS1307_CONTROL 0x07 ///< Control register
#define DS1307_NVRAM 0x08 ///< Start of RAM registers - 56 bytes, 0x08 to 0x3f
#define DS3231_ADDRESS 0x68 ///< I2C address for DS3231
#define DS3231_CONTROL 0x0E ///< Control register
#define DS3231_STATUSREG 0x0F ///< Status register
#define DS3231_TEMPERATUREREG 0x11 ///< Temperature register (high byte - low byte is at 0x12), 10-bit temperature value
/** Constants */
#define SECONDS_PER_DAY 86400L ///< 60 * 60 * 24
#define SECONDS_FROM_1970_TO_2000 946684800 ///< Unixtime for 2000-01-01 00:00:00, useful for initialization
/**************************************************************************/
/*!
@brief Simple general-purpose date/time class (no TZ / DST / leap second handling!).
See http://en.wikipedia.org/wiki/Leap_second
*/
/**************************************************************************/
class DateTime {
public:
DateTime (uint32_t t = SECONDS_FROM_1970_TO_2000);
DateTime (uint16_t year, uint8_t month, uint8_t day,
uint8_t hour = 0, uint8_t min = 0, uint8_t sec = 0);
DateTime (const DateTime& copy);
DateTime (const char* date, const char* time);
DateTime (const __FlashStringHelper* date, const __FlashStringHelper* time);
/*!
@brief Return the year, stored as an offset from 2000
@return uint16_t year
*/
uint16_t year() const { return 2000 + yOff; }
/*!
@brief Return month
@return uint8_t month
*/
uint8_t month() const { return m; }
/*!
@brief Return day
@return uint8_t day
*/
uint8_t day() const { return d; }
/*!
@brief Return hours
@return uint8_t hours
*/
uint8_t hour() const { return hh; }
/*!
@brief Return minutes
@return uint8_t minutes
*/
uint8_t minute() const { return mm; }
/*!
@brief Return seconds
@return uint8_t seconds
*/
uint8_t second() const { return ss; }
uint8_t dayOfTheWeek() const;
/** 32-bit times as seconds since 1/1/2000 */
long secondstime() const;
/** 32-bit times as seconds since 1/1/1970 */
uint32_t unixtime(void) const;
/** ISO 8601 Timestamp function */
enum timestampOpt{
TIMESTAMP_FULL, // YYYY-MM-DDTHH:MM:SS
TIMESTAMP_TIME, // HH:MM:SS
TIMESTAMP_DATE // YYYY-MM-DD
};
String timestamp(timestampOpt opt = TIMESTAMP_FULL);
DateTime operator+(const TimeSpan& span);
DateTime operator-(const TimeSpan& span);
TimeSpan operator-(const DateTime& right);
bool operator<(const DateTime& right) const;
/*!
@brief Test if one DateTime is greater (later) than another
@param right DateTime object to compare
@return True if the left object is greater than the right object, false otherwise
*/
bool operator>(const DateTime& right) const { return right < *this; }
/*!
@brief Test if one DateTime is less (earlier) than or equal to another
@param right DateTime object to compare
@return True if the left object is less than or equal to the right object, false otherwise
*/
bool operator<=(const DateTime& right) const { return !(*this > right); }
/*!
@brief Test if one DateTime is greater (later) than or equal to another
@param right DateTime object to compare
@return True if the left object is greater than or equal to the right object, false otherwise
*/
bool operator>=(const DateTime& right) const { return !(*this < right); }
bool operator==(const DateTime& right) const;
/*!
@brief Test if two DateTime objects not equal
@param right DateTime object to compare
@return True if the two objects are not equal, false if they are
*/
bool operator!=(const DateTime& right) const { return !(*this == right); }
protected:
uint8_t yOff; ///< Year offset from 2000
uint8_t m; ///< Month 1-12
uint8_t d; ///< Day 1-31
uint8_t hh; ///< Hours 0-23
uint8_t mm; ///< Minutes 0-59
uint8_t ss; ///< Seconds 0-59
};
/**************************************************************************/
/*!
@brief Timespan which can represent changes in time with seconds accuracy.
*/
/**************************************************************************/
class TimeSpan {
public:
TimeSpan (int32_t seconds = 0);
TimeSpan (int16_t days, int8_t hours, int8_t minutes, int8_t seconds);
TimeSpan (const TimeSpan& copy);
/*!
@brief Number of days in the TimeSpan
e.g. 4
@return int16_t days
*/
int16_t days() const { return _seconds / 86400L; }
/*!
@brief Number of hours in the TimeSpan
This is not the total hours, it includes the days
e.g. 4 days, 3 hours - NOT 99 hours
@return int8_t hours
*/
int8_t hours() const { return _seconds / 3600 % 24; }
/*!
@brief Number of minutes in the TimeSpan
This is not the total minutes, it includes days/hours
e.g. 4 days, 3 hours, 27 minutes
@return int8_t minutes
*/
int8_t minutes() const { return _seconds / 60 % 60; }
/*!
@brief Number of seconds in the TimeSpan
This is not the total seconds, it includes the days/hours/minutes
e.g. 4 days, 3 hours, 27 minutes, 7 seconds
@return int8_t seconds
*/
int8_t seconds() const { return _seconds % 60; }
/*!
@brief Total number of seconds in the TimeSpan, e.g. 358027
@return int32_t seconds
*/
int32_t totalseconds() const { return _seconds; }
TimeSpan operator+(const TimeSpan& right);
TimeSpan operator-(const TimeSpan& right);
protected:
int32_t _seconds; ///< Actual TimeSpan value is stored as seconds
};
/** DS1307 SQW pin mode settings */
enum Ds1307SqwPinMode {
DS1307_OFF = 0x00, // Low
DS1307_ON = 0x80, // High
DS1307_SquareWave1HZ = 0x10, // 1Hz square wave
DS1307_SquareWave4kHz = 0x11, // 4kHz square wave
DS1307_SquareWave8kHz = 0x12, // 8kHz square wave
DS1307_SquareWave32kHz = 0x13 // 32kHz square wave
};
/**************************************************************************/
/*!
@brief RTC based on the DS1307 chip connected via I2C and the Wire library
*/
/**************************************************************************/
class RTC_DS1307 {
public:
boolean begin(void);
static void adjust(const DateTime& dt);
uint8_t isrunning(void);
static DateTime now();
static Ds1307SqwPinMode readSqwPinMode();
static void writeSqwPinMode(Ds1307SqwPinMode mode);
uint8_t readnvram(uint8_t address);
void readnvram(uint8_t* buf, uint8_t size, uint8_t address);
void writenvram(uint8_t address, uint8_t data);
void writenvram(uint8_t address, uint8_t* buf, uint8_t size);
};
/** DS3231 SQW pin mode settings */
enum Ds3231SqwPinMode {
DS3231_OFF = 0x01, // Off
DS3231_SquareWave1Hz = 0x00, // 1Hz square wave
DS3231_SquareWave1kHz = 0x08, // 1kHz square wave
DS3231_SquareWave4kHz = 0x10, // 4kHz square wave
DS3231_SquareWave8kHz = 0x18 // 8kHz square wave
};
/**************************************************************************/
/*!
@brief RTC based on the DS3231 chip connected via I2C and the Wire library
*/
/**************************************************************************/
class RTC_DS3231 {
public:
boolean begin(void);
static void adjust(const DateTime& dt);
bool lostPower(void);
static DateTime now();
static Ds3231SqwPinMode readSqwPinMode();
static void writeSqwPinMode(Ds3231SqwPinMode mode);
static float getTemperature(); // in Celcius degree
};
/** PCF8523 SQW pin mode settings */
enum Pcf8523SqwPinMode {
PCF8523_OFF = 7, // Off
PCF8523_SquareWave1HZ = 6, // 1Hz square wave
PCF8523_SquareWave32HZ = 5, // 32Hz square wave
PCF8523_SquareWave1kHz = 4, // 1kHz square wave
PCF8523_SquareWave4kHz = 3, // 4kHz square wave
PCF8523_SquareWave8kHz = 2, // 8kHz square wave
PCF8523_SquareWave16kHz = 1, // 16kHz square wave
PCF8523_SquareWave32kHz = 0 // 32kHz square wave
};
/** PCF8523 Offset modes for making temperature/aging/accuracy adjustments */
enum Pcf8523OffsetMode {
PCF8523_TwoHours = 0x00, // Offset made every two hours
PCF8523_OneMinute = 0x80 // Offset made every minute
};
/**************************************************************************/
/*!
@brief RTC based on the PCF8523 chip connected via I2C and the Wire library
*/
/**************************************************************************/
class RTC_PCF8523 {
public:
boolean begin(void);
void adjust(const DateTime& dt);
boolean initialized(void);
static DateTime now();
Pcf8523SqwPinMode readSqwPinMode();
void writeSqwPinMode(Pcf8523SqwPinMode mode);
void calibrate(Pcf8523OffsetMode mode, int8_t offset);
};
/**************************************************************************/
/*!
@brief RTC using the internal millis() clock, has to be initialized before use.
NOTE: this is immune to millis() rollover events.
*/
/**************************************************************************/
class RTC_Millis {
public:
/*!
@brief Start the RTC
@param dt DateTime object with the date/time to set
*/
static void begin(const DateTime& dt) { adjust(dt); }
static void adjust(const DateTime& dt);
static DateTime now();
protected:
static uint32_t lastUnix; ///< Unix time from the previous call to now() - prevents rollover issues
static uint32_t lastMillis; ///< the millis() value corresponding to the last **full second** of Unix time
};
/**************************************************************************/
/*!
@brief RTC using the internal micros() clock, has to be initialized before
use. Unlike RTC_Millis, this can be tuned in order to compensate for
the natural drift of the system clock. Note that now() has to be
called more frequently than the micros() rollover period, which is
approximately 71.6 minutes.
*/
/**************************************************************************/
class RTC_Micros {
public:
/*!
@brief Start the RTC
@param dt DateTime object with the date/time to set
*/
static void begin(const DateTime& dt) { adjust(dt); }
static void adjust(const DateTime& dt);
static void adjustDrift(int ppm);
static DateTime now();
protected:
static uint32_t microsPerSecond; ///< Number of microseconds reported by micros() per "true" (calibrated) second
static uint32_t lastUnix; ///< Unix time from the previous call to now() - prevents rollover issues
static uint32_t lastMicros; ///< micros() value corresponding to the last full second of Unix time
};
#endif // _RTCLIB_H_
'임베디드 > 아두이노' 카테고리의 다른 글
아두이노 map함수, constrain함수 (1) | 2024.04.30 |
---|---|
아두이노 조도센서 (CDS, LDR, 포토셀, 포토레지스터) 연결하기 (0) | 2024.04.30 |