Tinkering with Time

Protocols and Programming

Many embedded systems need to make use of synchronized time information. In this article, Jeff explores the history of time measurement and how it has led to NTP and other modern technologies for coordinating universal date and time. Using Arduino and the Espressif System’s ESP32, Jeff then goes through the steps needed to enable an embedded system to request, retrieve and display the synchronized date and time to a display.
(Caption for lead image Figure 1: Time zone boundaries are flexible, shifted locally to keep territories from being divided wherever possible..

By Jeff Bachiochi

It’s been said that ”If you are on time, you’re late,” or, “To be early is to be on time.” It’s all relative. If you go to a meeting and people are already there, you feel as if you are late. If you are the first to arrive, you wonder if you’ve got the schedule wrong, and then you check your watch or phone for the time. Time can be troublesome for us, because the present is an ever-changing instant where the past meets the future. We cruise through life when all players reference the same moment, but should we become out of sync, the ride gets bumpy.

We can imagine that in humanity’s early times the first concepts of time were cyclic periods—like day/night, seasons and life/death. Our fundamental measurement of a day directly relates to our life and history, and seems to tie all nature together. But what about those activities that occur within the confines of each day? Some way of defining the parts of a day were needed. At the time, we had one division—day/night—with most considering the start of a day to be daybreak or sunrise, and the start of night to be sunset.

Since daytime was directly related to the sun’s position, the day could be divided into two parts based on whether the sun was rising in the sky or falling back toward the horizon. Observing the sun’s shadow gave way to the first sundials, which provided a visual indication of time relative to sunrise and sunset without physical divisions. One such division of the day was religious in origin: canonical hours or periods of fixed prayer at regular intervals were defined in monastic communities. At that time, our understanding of the sky was astrological and not astronomical. The latter would eventually define the breakdown of a day into hours, minutes and seconds.

For the most part, the hour was a variable concept. Around the 14th century, 12 was chosen as a practical division of the day (and the night) into equal parts. It was the most convenient number for dividing into fractions because it’s divisible by 2, 3 and 4—thus giving us the 24-hour day we use today. Without the sun, sundials were worthless, so other means of recording the passage of time were invented, including water, candles and weights. These and early mechanical clocks of the 16th century were not accurate, because their mechanisms were essentially unregulated. It wasn’t until the next century that the pendulum gave the mechanical clock accuracy to within 1 minute a day. Today, we have access to extremely accurate clocks. Atomic clocks measure an atom’s fluctuating energy levels to produce an accuracy of ± 1 second in over a billion years.

Time Keeper

The International Bureau of Weights and Measures (called Bureau International des Poids et Mesures or BIPM in France) is an intergovernmental organization that was established to oversee measurement science and measurement standards. One important role for the BIPM is maintaining the accuracy of worldwide time of day. It combines, analyzes and averages the official atomic time standards of member nations around the world, to create a single, official Coordinated Universal Time (UTC). The Royal Observatory, Greenwich, England was chosen as the reference point to define the Universal day, counted from 0 hours at mean midnight, as used on the island since 1847. By 1884, the Greenwich Meridian was used for two-thirds of all charts and maps as their Prime Meridian. The world is divided into 24 time zones, each 15 degrees in width (24 hr/360 degrees). However, as shown in Figure 1, time zone boundaries are shifted to prevent a country from being needlessly split into separate zones.

All time on earth is related to the official time in Greenwich, England by denoting a time zone offset. Current civil time can be determined by adding or subtracting the UTC offset (number of hours and minutes). This ranges from UTC−12:00 in the west to UTC+14:00 in the east. Table 1 lists those offsets that relate to the United States.
The US spans seven time zones. When a time zone uses daylight saving time, the ST for Standard Time is replaced by DT indicating Daylight Saving Time. Daylight Saving Time increases the regional offset by 1:00, and was implemented to shift daylight activities during the longer summer hours. Daylight Saving Time is a local shift that must be handled locally, and as such does not affect the UTC in any way.

Table 1
Time zone offsets are listed here for the US daylight saving times have an additional offset of 1 hour and must be accounted for locally.

In my youth I recall the phone company providing a number you could to call to hear the current time. The first radio station, WWV in Colorado, morphed into National Institute of Standards and Technology (NIST), whose broadcast focused on developing frequency standards and eventually broadcasting time and frequency information on the 2.5-, 5-, 10-, 15- and 20-MHz shortwave bands. Today, the time is available almost everywhere, and that time is synchronized to the UTC, all thanks to the Internet.

National Standard Time

The Network Time Protocol (NTP) is used to synchronize our clocks via the Internet. The NTP architecture, protocol and algorithms provide a nominal accuracy of tens of milliseconds on WANs, sub-milliseconds on LANs, and sub-microseconds using a precision time source such as a cesium oscillator or GPS receiver. Reliability is assured by redundant tiered servers and diverse network paths. The “NTP pool” is a dynamic collection of networked computers that volunteer to provide highly accurate time via the NTP to clients (like us) worldwide. We can use one of the NTP pool servers to get UTC information. Although using the NTP protocol will assure the accuracies listed above, this is often unnecessary and overly complicated for those applications that are only interested in whole-second times for RTC (Real Time Clocks). SNTP, a simplified subset of the NTP protocol, generally is sufficient for our needs.

Figure 2
This is the format of the 48 byte packet sent to and from NTP servers. We can get away with sending a packet of “zero” data, except for the first byte as a request. A received packet will contain the total seconds since the Epoch located in the first four bytes of the Transmit Timestamp.

SNTP uses a UDP connection to send a datagram or packet, as opposed to a TCP connection. The basic transaction is simple. We send an SNTP data structure as a UDP packet using port 123 to the server. The time server (one of the NTP pool) then sends back an SNTP data structure as a UDP packet. That’s it! The structure of the datagram consists of four 32-bit words (4 × 32 bits = 128 bits or 16 bytes), followed by four 64-bit time stamps (4 × 64 bits = 256 b or 32 bytes) as shown in Figure 2. There can be optional data, but we won’t need it. In fact, we need only to worry about the first byte of the (16 bytes + 32 bytes = 48 bytes) datagram to make a request.

This is set according to RFC 4330:

LeapsecondInformation 2 bits = “00” disregarded
             VersionNumber 3 bits = “100” 4
                        MODE 3 bits = “011” Client
Therefore:
First Byte = “00100011” or 0x23

The returned datagram will be in the same format. The time stamps we sent as zeros could have been used to determine the actual propagation delay in the message trip, to calculate an accurate sub-second synchronized time. We are not concerned with that level of accuracy. However, we do want to get the time from the server, and that will be populated in the last of the four time stamps in the reply. So how does this time stamp relate to the present second, minute, hour, day, month and year? Sad to say, it does not specify any of those. This time stamp gives the number of seconds from 0:00 on 1 January 1900. …

Read the full article in the February 343 issue of Circuit Cellar
(Full article word count: 3269 words; Figure count: 5 Figures.)

Don’t miss out on upcoming issues of Circuit Cellar. Subscribe today!

Note: We’ve made the October 2017 issue of Circuit Cellar available as a free sample issue. In it, you’ll find a rich variety of the kinds of articles and information that exemplify a typical issue of the current magazine.

NB-IoT Module is Ready for 3GPP Release 14 and 5G

U‑blox has announced the SARA‑N3, a multi‑band NB‑IoT module that supports a preliminary set of 3GPP Release 14 features (LTE Cat NB2). The SARA‑N3 is available in two variants: one dedicated to China and another that can operate across multiple bands on any NB‑IoT network globally. The U‑blox firmware‑over‑the‑air (uFOTA) client/server solution with Lightweight M2M (LwM2M) allows SARA‑N3 to be remotely provisioned with additional features.

LwM2M is a more lightweight solution as compared to OMA‑DM. That means it is well suited for providing critical firmware updates to IoT devices. In this way, SARA‑N3 can ultimately become 5G compliant. SARA‑N3 also supports the creation of dynamic LwM2M objects. That enables users to do feature customization by scripting their own configurable objects.

The SARA‑N3 provides a comprehensive set of features and protocols that NB‑IoT‑based applications will benefit from, including TCP, HTTPS, CoAP, DTLS and MQTT. With its ultra‑low power consumption profile and the ability to configure voltage domains, the module is optimized to operate on a single cell primary battery for 10+ years, eliminating the need for frequent maintenance visits. Other features include a “last gasp” function that lets the module send one last message should the power fail unexpectedly and protection against software attacks by detecting potential jamming signals.

U‑blox manufactures according to ISO/TS16949 professional grade specifications. This approach incorporates 100% automated x‑ray and optical inspections, 100% outgoing test and product traceability. Together with failure analysis and product qualification criteria ensures that highly reliable products designed for long‑term operation are created.

U‑blox | www.u‑blox.com

Fanless SBC Targets Industrial IoT

Technologic Systems is now shipping its newest single board computer, the TS-7553-V2. The board is developed around the NXP i.MX6 UltraLite, a high performance  processor family featuring an advanced implementation of a single ARM Cortex-A7 core, which operates at speeds up to 696 MHz. While able to support a wide range of embedded applications, the TS-7553-V2 was specifically designed to target the industrial Internet of Things (IIoT) sector.

ts-7553-v2The TS-7553-V2 was designed with connectivity in mind. An on-board Xbee interface, capable of supporting Xbee or NimbleLink, provides a simple path to adding a variety of Wireless interfaces. An Xbee radio can be used to link in with a local 2.4GHz or sub 1 GHz mesh networks, allowing for gateway or node deployments. Either Digi or NimbleLink offer cellular radios for this socket, providing cellular connectivity for applications such as remote equipment monitoring and control. There is also the option for a cellular modem via daughter card. This allows transmission of serial data via TCP, UDP or SMS over the cellular network. The TS-7553-V2 also includes an on board WiFi b/g/n and Bluetooth 4.0 option, providing even more connectivity.

Further radio expansion can be accomplished with the two internal USB interfaces (one on a standard USB Type A connector, and the second on simple pin headers). The USB interfaces enable support for multiple proprietary networks via a dongle or USB connected device. This provides the opportunity to run mesh, LoRa, ZigBee, automotive WiFi or other protocols with the TS-7553-v2 . All of these radio options combined with the on board 10/100Base-T Ethernet create the opportunity to communicate seamlessly with up to 5 different networks simultaneously from a single point.

The TS-75553-V2 supports standard interfaces including:

  •     10/100 Ethernet
  •     TTL UART
  •     4 USB ports (3 host interfaces and, 1 device)
  •     3 RS-232 Serial/COM ports
  •     RS-485 port
  •     CAN bus
  •     Up to 5 GPIO

A Nine-Axis Micro-Electro-Mechanical System (MEMS) motion tracking device containing a gyroscope, accelerometer and compass are optional on-board in for asset management, fleet management and other applications which would require sensing motion or vibration in the environment.

A low cost monochrome 128x64px LCD with 4 button keypad is available for Human Machine Interface (HMI) applications.  The keypad offers intuitive operation using 4 tactile function keys and the LCD is ideal for simple visualization tasks, even in harsh environments.  If HMI is not a consideration compact, lightweight, rugged enclosures are available to contain your gateway in a secure fanless enclosure. Both enclosures are DIN mountable.

Technologic Systems has taken the lead in combating read/write errors to memory that can prove fatal to Operating Systems. TS-SILO is an optional feature which will provide up to 30 seconds of reserve power in the event of a power failure. This precious extra time gives the board time to gracefully power down and ensures file system integrity. Additionally, for heavy data logging applications The TS-7553-V2 is the first SBC from Technologic Systems to include Ferroelectric RAM (FeRAM or FRAM). FeRAM advantages over flash include: lower power usage, faster write performance and a much greater maximum read/write endurance, allowing a user to keep running data logs without prematurely wearing out their flash memory. Combined these two features provide you with insurance from abrupt power loss, read/write errors and startup difficulties.

Applications with strict low power requirements will appreciate the work that’s been done to reduce power consumption to less than 2 W in typical conditions and a 9 mW sleep mode. Power over Ethernet (PoE) is supported via a daughter card, if desired.

Development can begin out-of-the-box with pre-installed Linux and utilities for controlling DIO, UARTS, CAN bus, and more. A complete board support package is provided, as well as access to our software repository and online support. Third party application support can be provided via the Technologic Systems’ Partner Network.

Technologic Systems | www.embeddedARM.com