Setting RTC From Internet?

All ESP8266 boards running MicroPython.
Official boards are the Adafruit Huzzah and Feather boards.
Target audience: MicroPython users with an ESP8266 board.
weldeng
Posts: 31
Joined: Thu Sep 15, 2016 12:47 am

Setting RTC From Internet?

Post by weldeng » Mon Sep 26, 2016 11:30 pm

Does anyone have Miicropython Code they could share on how to set the real time clock of the ESP8266 from the internet?

Thanks

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Setting RTC From Internet?

Post by pythoncoder » Tue Sep 27, 2016 6:53 am

See https://github.com/micropython/micropyt ... ntptime.py. The module ntptime is available by default so you only need to issue

Code: Select all

import ntptime
to use it.
Peter Hinch
Index to my micropython libraries.

weldeng
Posts: 31
Joined: Thu Sep 15, 2016 12:47 am

Re: Setting RTC From Internet?

Post by weldeng » Tue Sep 27, 2016 9:59 pm

pythoncoder wrote:See https://github.com/micropython/micropyt ... ntptime.py. The module ntptime is available by default so you only need to issue

Code: Select all

import ntptime
to use it.
Not sure how to use this!

In a August 16th post deshipu gave an easy explaination on how to manually set the RTC (below)
>>>import machine
>>>rtc=machine.RTC()
>>>rtc.datetime((2014, 5, 1, 0, 4, 13, 0, 0))
>>>rtc.datetime()
(2014, 5, 1, 0, 4, 13, 0, 0)

I am running on battery power and entering deep sleep mode periodically. ESP8266 resets time on waking. I would like to replace the 2nd line of Code above with a call out to the internet to get the time after waking from deepsleep. I am not sure how to use ntptime as you suggest to accomplish this. Any additional assistance is greatly appreciated.

User avatar
Roberthh
Posts: 3667
Joined: Sat May 09, 2015 4:13 pm
Location: Rhineland, Europe

Re: Setting RTC From Internet?

Post by Roberthh » Wed Sep 28, 2016 4:18 am

That's what I am using to set the time after boot:

Code: Select all

from ntptime import settime
settime()

weldeng
Posts: 31
Joined: Thu Sep 15, 2016 12:47 am

Re: Setting RTC From Internet?

Post by weldeng » Wed Sep 28, 2016 9:50 pm

Roberthh wrote:That's what I am using to set the time after boot:

Code: Select all

from ntptime import settime
settime()
>>> from ntptime import settime
>>> settime()

got this error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "ntptime.py", line 30, in settime
File "ntptime.py", line 22, in time
OSError: [Errno 110] ETIMEDOUT

Repowered and tried it again and the second time it worked
>>> from ntptime import settime
>>> settime()
(2016, 9, 28, 21, 43, 27, 2, 272)
>>>

Not sure what wrong the first time but I am going to have to figure out some error handling to account for this happening.

Thanks for the help!!

User avatar
Roberthh
Posts: 3667
Joined: Sat May 09, 2015 4:13 pm
Location: Rhineland, Europe

Re: Setting RTC From Internet?

Post by Roberthh » Thu Sep 29, 2016 5:25 am

settime) requires a connection to an NTP server. In my set-up, it sometimes takes a while until the ESP8266 connect to my access point. The do_connect() function from the example waits until this connection is established or runs into a timeout, with exactly the errors you report. This is the exmaple function:

Code: Select all

def do_connect():
	import network, time
	sta_if = network.WLAN(network.STA_IF)
	if not sta_if.isconnected():
		print('connecting to network...')
		sta_if.active(True)
		sta_if.connect('ap-name', 'password')
		while not sta_if.isconnected():	
			pass
	print('network config:', sta_if.ifconfig())
You may get the timeout there. After I replaced the wait loop by:

Code: Select all

		while not sta_if.isconnected():	
			print(".", end="")
			time.sleep(1)
the connections is always established.

NTL2009
Posts: 20
Joined: Wed Oct 26, 2016 10:07 pm

Re: Setting RTC From Internet?

Post by NTL2009 » Tue Nov 01, 2016 2:05 am

So I entered the code above to connect to my local wi-fi network (which I've used OK before), and then executed the commands:

>>> from ntptime import settime
>>> settime()
(2016, 11, 1, 1, 55, 21, 1, 306)

and the data returned was the current GMT time, so it obviously got out to the pool.ntp.org servers and updated my ESP board. So far so good!

Format looks to be (year, month, day, hours, minutes, seconds, weekday, yearday), with Monday = 0 weekday.

But now I'm stuck. How do I pull that data out to use in my program? I'm new at this, so if you can , please give specifics, like which command and what variables it can be read into. I don't know if the settime() can be read into a variable (I haven't figured out how - it seems to be only for updating the clock, and it reports back the status?). What, and how, do I read the current time to use n my program? I've searched, but I'm lost.

chrisgp
Posts: 41
Joined: Fri Apr 01, 2016 5:29 pm

Re: Setting RTC From Internet?

Post by chrisgp » Tue Nov 01, 2016 2:23 am

Check out utime and machine.RTC. Their functions will give the appropriate time once you've made the NTP call to sync up.

For example utime.localtime() will return back a tuple with the various fields available.

NTL2009
Posts: 20
Joined: Wed Oct 26, 2016 10:07 pm

Re: Setting RTC From Internet?

Post by NTL2009 » Tue Nov 01, 2016 2:36 am

chrisgp wrote:Check out utime and machine.RTC. Their functions will give the appropriate time once you've made the NTP call to sync up.

For example utime.localtime() will return back a tuple with the various fields available.
Thanks, I came across each of those in my previous searches, but since I'm so new to this, I don't know how to actually implement those instructions in a program. I haven't found actual code examples. So far, I've been able to figure things like this out, but I'm just stuck on the actual implementation of any of those commands. Probably a mental block on my part, but I'm stuck. Code examples would really help me get over this bump.

UPDATE: OK, I think I'm getting there...

>>> import utime
>>> utime.localtime()
(2016, 11, 1, 2, 41, 43, 1, 306)
>>> ts = utime.localtime()
>>> ts
(2016, 11, 1, 2, 42, 44, 1, 306)

# (YYYY, MM, DD, HH, MM, SS, Day of week [Monday=0], Day of year)
# ts[0] returns 2016; ts[7] returns 306
# ts[0:7] returns(2016, 11, 1, 2, 42, 44, 1)

chrisgp
Posts: 41
Joined: Fri Apr 01, 2016 5:29 pm

Re: Setting RTC From Internet?

Post by chrisgp » Tue Nov 01, 2016 4:11 am

Here's a simple example. It prints the day of the week and the month in textual format. After that it goes into a loop where it prints a message once each Tuesday by watching a triggered flag.

Code: Select all

(year, month, mday, hour, minute, second, weekday, yearday) = utime.localtime()

days= {0:"Monday", 1:"Tuesday", 2:"Wednesday", 3:"Thursday", 4:"Friday", 5:"Saturday", 6:"Sunday"}
months = {1:"January", 2:"February", 3:"March", 4:"April", 5:"May", 6:"June", 7:"July", 8:"August", 9:"September", 10:"October", 11:"November", 12:"December"}

print("Today is {}".format(days[weekday]))
print("The month is {}".format(months[month]))

triggered = False
while True:
    time.sleep(1)
    (year, month, mday, hour, minute, second, weekday, yearday) = utime.localtime()
    if weekday != 1:
        triggered = False
    elif not triggered:
        triggered = True
        print("I execute once each Tuesday.")

Code: Select all

>>> 
paste mode; Ctrl-C to cancel, Ctrl-D to finish
=== (year, month, mday, hour, minute, second, weekday, yearday) = utime.localtime()
=== 
=== days= {0:"Monday", 1:"Tuesday", 2:"Wednesday", 3:"Thursday", 4:"Friday", 5:"Saturday", 6:"Sunday"}
=== months = {1:"January", 2:"February", 3:"March", 4:"April", 5:"May", 6:"June", 7:"July", 8:"August", 9:"September", 10:"October", 11:"November", 12:"December"}
=== 
=== print("Today is {}".format(days[weekday]))
=== print("The month is {}".format(months[month]))
=== 
=== triggered = False
=== while True:
===     time.sleep(1)
===     (year, month, mday, hour, minute, second, weekday, yearday) = utime.localtime()
===     if weekday != 1:
===         triggered = False
===     elif not triggered:
===         triggered = True
===         print("I execute once each Tuesday.")
=== 
Today is Tuesday
The month is November
I execute once each Tuesday.

Post Reply