1083 views|1 replies

19

Posts

0

Resources
The OP
 

[Digi-Key Follow me Issue 1] Part 3: Networking and time synchronization + ntp delta update [Copy link]

 This post was last edited by sss421 on 2023-6-3 23:52

The content of networking and time synchronization is introduced in detail in the first open class.

The wifi module is an onboard module and does not require any hardware connection.

The networking part of the wifi module is implemented as follows:

import network
import time
ssid = 'XXX'
password = 'XXXXX'
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
# Wait for connect or fail
max_wait = 10
while max_wait > 0:
  if wlan.status() < 0 or wlan.status() >= 3:
    break
  max_wait -= 1
  print('waiting for connection...')
  time.sleep(1)
# Handle connection error
if wlan.status() != 3:
  raise RuntimeError('network connection failed')
else:
  print('connected')
  status = wlan.ifconfig()
  print('ip = ' + status[0])


After successful networking, the current IP will be printed

raw REPL; CTRL-B to exit

>OK

waiting for connection...

waiting for connection...

waiting for connection...

waiting for connection...

waiting for connection...

waiting for connection...

connected

ip = 192.168.2.115

Below is the display code with OLED


import network
import time
ssid = 'xxx'
password = 'xxx'
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
# Wait for connect or fail
max_wait = 10
while max_wait > 0:
  if wlan.status() < 0 or wlan.status() >= 3:
    break
  max_wait -= 1
  print('waiting for connection...')
  time.sleep(1)
# Handle connection error
if wlan.status() != 3:
  raise RuntimeError('network connection failed')
else:
  print('connected')
  status = wlan.ifconfig()
  print('ip = ' + status[0])
# 在这里写上你的代码 :-)
import ntptime
def sync_ntp():
  ntptime.NTP_DELTA = 3155644800  # 可选 UTC+8偏移时间(秒),不设置就是UTC0
  ntptime.host = 'ntp1.aliyun.com' # 可选,ntp服务器,默认是"pool.ntp.org"
  ntptime.settime()  # 修改设备时间,到这就已经设置好了
sync_ntp()
from machine import RTC
from time import sleep
i2c = I2C(1, scl=Pin(7), sda=Pin(6), freq=400000) # Grove - OLED Display 0.96" (SSD1315)
oled = SSD1306_I2C(128, 64, i2c)
oled.fill(0) # clear
oled.text("NTP Time!", 0, 0)
oled.show()
while True:
  rtc = RTC()
  print(rtc.datetime())
  oled.fill(0) # clear
  oled.text("NTP Time!", 0, 0)
  s = ','.join(str(i) for i in rtc.datetime())
  oled.text(s, 0, 16)
  oled.show()
  sleep(1)

Final result:

waiting for connection...

waiting for connection...

connected

ip = 192.168.2.115

(2023, 6, 1, 3, 14, 55, 21, 0)

(2023, 6, 1, 3, 14, 55, 22, 0)

(2023, 6, 1, 3, 14, 55, 23, 0)

(2023, 6, 1, 3, 14, 55, 24, 0)

(2023, 6, 1, 3, 14, 55, 25, 0)

(2023, 6, 1, 3, 14, 55, 26, 0)

(2023, 6, 1, 3, 14, 55, 27, 0)

(2023, 6, 1, 3, 14, 55, 28, 0)

(2023, 6, 1, 3, 14, 55, 29, 0)

(2023, 6, 1, 3, 14, 55, 30, 0)

Update, found that the UTC modification is not effective, with the help of the big guys, found that it was caused by the update of the utptime library

    EPOCH_YEAR = utime.gmtime(0)[0]
    if EPOCH_YEAR == 2000:
        # (date(2000, 1, 1) - date(1900, 1, 1)).days * 24*60*60
        NTP_DELTA = 3155673600
    elif EPOCH_YEAR == 1970:
        # (date(1970, 1, 1) - date(1900, 1, 1)).days * 24*60*60
        NTP_DELTA = 2208988800
    else:
        raise Exception("Unsupported epoch: {}".format(EPOCH_YEAR))

Added support for different EPOCH_YEAR, which makes the tricky NTP_DELTA setting invalid

The ntptime library is personalized, and a UTC_DELTA variable is added. The final code is as follows:

from ssd1306 import SSD1306_I2C
import network
import time

ssid = 'xxx'
password = 'xxxx'

wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)

# Wait for connect or fail
max_wait = 10
while max_wait > 0:
    if wlan.status() < 0 or wlan.status() >= 3:
        break
    max_wait -= 1
    print('waiting for connection...')
    time.sleep(1)

# Handle connection error
if wlan.status() != 3:
    raise RuntimeError('network connection failed')
else:
    print('connected')
    status = wlan.ifconfig()
    print('ip = ' + status[0])
# 在这里写上你的代码 :-)
import ntptime
def sync_ntp():
     ntptime.UTC_DELTA = 28800 # 可选 UTC+8偏移时间(秒),不设置就是UTC0
     ntptime.host = 'ntp1.aliyun.com'  # 可选,ntp服务器,默认是"pool.ntp.org"
     ntptime.settime()   # 修改设备时间,到这就已经设置好了

sync_ntp()

from machine import RTC,I2C,Pin
from time import sleep

i2c = I2C(1, scl=Pin(7), sda=Pin(6), freq=400000)  # Grove - OLED Display 0.96" (SSD1315)
oled = SSD1306_I2C(128, 64, i2c)
oled.fill(0)  # clear
oled.text("NTP Time!", 0, 0)
oled.show()
while True:
    rtc = RTC()
    print(rtc.datetime())
    oled.fill(0)  # clear
    oled.text("NTP Time!", 0, 0)
    s = ','.join(str(i) for i in rtc.datetime())
    oled.text(s, 0, 16)
    oled.show()
    sleep(1)

Modified ntptime.py

import utime

try:
    import usocket as socket
except:
    import socket
try:
    import ustruct as struct
except:
    import struct

# The NTP host can be configured at runtime by doing: ntptime.host = 'myhost.org'
host = "pool.ntp.org"
# The NTP socket timeout can be configured at runtime by doing: ntptime.timeout = 2
timeout = 1


def time():
    NTP_QUERY = bytearray(48)
    NTP_QUERY[0] = 0x1B
    addr = socket.getaddrinfo(host, 123)[0][-1]
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.settimeout(timeout)
        res = s.sendto(NTP_QUERY, addr)
        msg = s.recv(48)
    finally:
        s.close()
    val = struct.unpack("!I", msg[40:44])[0]

    EPOCH_YEAR = utime.gmtime(0)[0]
    if EPOCH_YEAR == 2000:
        # (date(2000, 1, 1) - date(1900, 1, 1)).days * 24*60*60
        NTP_DELTA = 3155673600
    elif EPOCH_YEAR == 1970:
        # (date(1970, 1, 1) - date(1900, 1, 1)).days * 24*60*60
        NTP_DELTA = 2208988800
    else:
        raise Exception("Unsupported epoch: {}".format(EPOCH_YEAR))
    
    try:
        UTC_DELTA
    except NameError:
        pass
    else:
        NTP_DELTA = NTP_DELTA - UTC_DELTA

    return val - NTP_DELTA


# There's currently no timezone support in MicroPython, and the RTC is set in UTC time.
def settime():
    t = time()
    import machine

    tm = utime.gmtime(t)
    machine.RTC().datetime((tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0))

This post is from DigiKey Technology Zone

Latest reply

This code is long enough.   Details Published on 2023-6-3 10:51
 
 

6570

Posts

0

Resources
2
 

This code is long enough.

This post is from DigiKey Technology Zone
 
 
 

Just looking around
Find a datasheet?

EEWorld Datasheet Technical Support

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京B2-20211791 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号
快速回复 返回顶部 Return list