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.

February Circuit Cellar: Sneak Preview

The February issue of Circuit Cellar magazine is coming soon. We’ve raised up a bumper crop of in-depth embedded electronics articles just for you, and packed ’em into our 84-page magazine.

Not a Circuit Cellar subscriber?  Don’t be left out! Sign up today:

 

Here’s a sneak preview of February 2019 Circuit Cellar:

MCUs ARE EVERYWHERE, DOING EVERYTHING

Electronics for Automotive Infotainment
As automotive dashboard displays get more sophisticated, information and entertainment are merging into so-called infotainment systems. That’s driving a need for powerful MCU- and MPU-based solutions that support the connectivity, computing and interfacing needs particular to these system designs. In this article, Circuit Cellar’s Editor-in-Chief, Jeff Child, looks at the technology and trends feuling automotive infotainment.

Inductive Sensing with PSoC MCUs
Inductive sensing is shaping up to be the next big thing for touch technology. It’s suited for applications involving metal-over-touch situations in automotive, industrial and other similar systems. In his article, Nishant Mittal explores the science and technology of inductive sensing. He then describes a complete system design, along with firmware, for an inductive sensing solution based on Cypress Semiconductor’s PSoC microcontroller.

Build a Self-Correcting LED Clock
In North America, most radio-controlled clocks use WWVB’s transmissions to set the correct time. WWVB is a Colorado-based time signal radio station near. Learn how Cornell graduates Eldar Slobodyan and Jason Ben Nathan designed and built a prototype of a Digital WWVB Clock. The project’s main components include a Microchip PIC32 MCU, an external oscillator and a display.

WE’VE GOT THE POWER

Product Focus: ADCs and DACs
Analog-to-digital converters (ADCs) and digital-to-analog converters (DACs) are two of the key IC components that enable digital systems to interact with the real world. Makers of analog ICs are constantly evolving their DAC and ADC chips pushing the barriers of resolution and speeds. This new Product Focus section updates readers on this technology and provides a product album of representative ADC and DAC products.

Building a Generator Control System
Three phase electrical power is a critical technology for heavy machinery. Learn how US Coast Guard Academy students Kent Altobelli and Caleb Stewart built a physical generator set model capable of producing three phase electricity. The article steps through the power sensors, master controller and DC-DC conversion design choices they faced with this project.

EMBEDDED COMPUTING FOR YOUR SYSTEM DESIGN

Non-Standard Single Board Computers
Although standard-form factor embedded computers provide a lot of value, many applications demand that form take priority over function. That’s where non-standard boards shine. The majority of non-standard boards tend to be extremely compact, and well suited for size-constrained system designs. Circuit Cellar Chief Editor Jeff Child explores the latest technology trends and product developments in non-standard SBCs.

Thermal Management in machine learning
Artificial intelligence and machine learning continue to move toward center stage. But the powerful processing they require is tied to high power dissipation that results in a lot of heat to manage. In his article, Tom Gregory from 6SigmaET explores the alternatives available today with a special look at cooling Google’s Tensor Processor Unit 3.0 (TPUv3) which was designed with machine learning in mind.

… AND MORE FROM OUR EXPERT COLUMNISTS

Bluetooth Mesh (Part 1)
Wireless mesh networks are being widely deployed in a wide variety of settings. In this article, Bob Japenga begins his series on Bluetooth mesh. He starts with defining what a mesh network is, then looks at two alternatives available to you as embedded systems designers.

Implementing Time Technology
Many embedded systems need to make use of synchronized time information. In this article, Jeff Bachiochi explores the history of time measurement and how it’s 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 your embedded system to request, retrieve and display the synchronized date and time to a display.

Infrared Sensors
Infrared sensing technology has broad application ranging from motion detection in security systems to proximity switches in consumer devices. In this article, George Novacek looks at the science, technology and circuitry of infrared sensors. He also discusses the various types of infrared sensing technologies and how to use them.

The Art of Voltage Probing
Using the right tool for the right job is a basic tenant of electronics engineering. In this article, Robert Lacoste explores one of the most common tools on an engineer’s bench: oscilloscope probes, and in particular the voltage measurement probe. He looks and the different types of voltage probes as well as the techniques to use them effectively and safely.