Arduino time status

PaulStoffregen/Time

Use Git or checkout with SVN using the web URL.

Work fast with our official CLI. Learn more.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

Readme.md

Arduino Time Library

Time is a library that provides timekeeping functionality for Arduino.

Using the Arduino Library Manager, install «Time by Michael Margolis«.

The code is derived from the Playground DateTime library but is updated to provide an API that is more flexible 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.

To use the Time library in an Arduino sketch, include TimeLib.h.

The functions available in the library include

there are also functions to return the hour in 12-hour format

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 problem

Functions for managing the timer services are:

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 .

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 characters) 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. The basic DS1307RTC library must be downloaded and installed, in order to run this sketch.

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 very simple logger application that monitors events on digital 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 separate library
  • time elements can be accessed non-atomically (in DateTime they are always atomic)
  • function added to automatically sync time with external source
  • localTime and maketime parameters changed, localTime renamed to breakTime

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:

This DS1307RTC library provides an example of how a time provider can use the low-level functions to interface with the Time library.

Источник

thorsten-l/TimeLib

Use Git or checkout with SVN using the web URL.

Work fast with our official CLI. Learn more.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

This branch is 2 commits ahead of PaulStoffregen:master.

Open a pull request to contribute your changes upstream.

Latest commit

Git stats

Files

Failed to load latest commit information.

Readme.md

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 flexible 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

there are also functions to return the hour in 12-hour format

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 problem

Functions for managing the timer services are:

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.

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 very simple logger application that monitors events on digital 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 separate library
  • time elements can be accessed non-atomically (in DateTime they are always atomic)
  • function added to automatically sync time with external source
  • localTime and maketime parameters changed, localTime renamed to breakTime

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:

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.

Источник

Функции времени

Задержки

Простейшей с точки зрения использования функцией времени является задержка: программа “зависает” внутри функции задержки и ожидает указанное время. Задержка позволяет очень удобно и наглядно организовать работу простой “однозадачной” программы, у нас есть два варианта задержек:

  • delay(time)
    • Задержка на указанное количество миллисекунд (мс). 1 секунда = 1’000 мс.
    • time принимает тип данных unsigned long и может приостановить выполнение на срок от 1 до 4 294 967 295 мс (

    50 суток) с разрешением 1 мс.

  • Работает на системном таймере, поэтому не работает внутри прерывания и при отключенных прерываниях.
  • delayMicroseconds(time)
    • Задержка на указанное количество микросекунд (мкс). 1 секунда = 1’000’000 мкс.
    • time принимает тип данных unsigned int и может приостановить выполнение на срок от 4 до 16383 мкс (да, меньше чем максимум для этого типа данных) с разрешением 4 мкс.
    • Работает не на таймере, а на пропуске тактов процессора, поэтому может работать в прерывании и при отключенных прерываниях.
    • Иногда не совсем корректно работает с переменными, поэтому нужно стараться использовать константы ( const или просто число).
    • Часто используется в библиотеках для эмуляции цифровых интерфейсов связи.
  • Задержки использовать очень просто:

    Мышление “задержками” – главная проблема новичков. Организовать работу сложной программы при помощи задержки – невозможно, поэтому дальше рассмотрим более полезные инструменты.

    Функция yield()

    Разработчики Arduino позаботились о том, чтобы функция delay() не просто блокировала выполнение кода, но и позволяла выполнять другой код во время этой задержки. Данный “костыль” получил название yield() и работает следующим образом: если объявить функцию

    то расположенный внутри неё код будет выполняться во время работы любой задержки delay() в программе! Это решение хоть и кажется нелепым, но в то же время позволяет быстро и без написания лишних костылей и таймеров реализовать пару параллельно выполняющихся задач. Это вполне соответствует идеологии Arduino – максимально простая и быстрая разработка прототипа. Рассмотрим простой пример: стандартный мигающий светодиод, но с опросом кнопки:

    Функции счёта времени

    Данные функции возвращают время, прошедшее с момента запуска программы, так называемый аптайм (англ. uptime). Таких функций у нас две:

      millis() – миллисекунды, тип unsigned long , от 1 до 4 294 967 295 мс (

    50 суток), разрешение 1 мс. После “переполнения” отсчёт начинается с нуля.
    micros() – микросекунды, тип unsigned long , от 4 до 4 294 967 295 мкс (

    70 минут), разрешение 4 мкс. После “переполнения” отсчёт начинается с нуля.

    Эти функции позволяют организовать программу практически любой сложности с любым количеством параллельно выполняющихся по таймеру задач. Подробнее об этом поговорим в уроке про многозадачность.

    millis() в часы и секунды

    Миллисекунды – не самый удобный способ оценить время работы программы. Можно перевести его в более человеческие часы, минуты и секунды при помощи нехитрых математических операций:

    Видео

    Источник

    Adblock
    detector