SNTP Module

Since Origin / Contributor Maintainer Source
2015-06-30 DiUS, Johny Mattsson Johny Mattsson sntp.c

The SNTP module implements a Simple Network Time Procotol client. This includes support for the "anycast" NTP mode where, if supported by the NTP server(s) in your network, it is not necessary to even know the IP address of the NTP server.

When compiled together with the rtctime module it also offers seamless integration with it, potentially reducing the process of obtaining NTP synchronization to a simple sntp.sync() call without any arguments.


Attempts to obtain time synchronization.

For best results you may want to to call this periodically in order to compensate for internal clock drift. As stated in the rtctime module documentation it's advisable to sync time after deep sleep and it's necessary to sync after module reset (add it to init.lua after WiFi initialization).


sntp.sync([server_ip], [callback], [errcallback])


  • server_ip if non-nil, that server is used. If nil, then the last contacted server is used. This ties in with the NTP anycast mode, where the first responding server is remembered for future synchronization requests. The easiest way to use anycast is to always pass nil for the server argument.
  • callback if provided it will be invoked on a successful synchronization, with three parameters: seconds, microseconds, and server. Note that when the rtctime module is available, there is no need to explicitly call rtctime.set() - this module takes care of doing so internally automatically, for best accuracy.
  • errcallback failure callback with a single integer parameter describing the type of error. The module automatically performs a number of retries before giving up and reporting the error. Error codes:
  • 1: DNS lookup failed
  • 2: Memory allocation failure
  • 3: UDP send failed
  • 4: Timeout, no NTP response received




-- Best effort, use the last known NTP server (or the NTP "anycast" address initially)
-- Sync time with and print the result, or that it failed
    print('sync', sec, usec, server)

See also