Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 5083

MicroPython • Re: pico onboard rtc and lack of datetime module

$
0
0
What about this code? I grabed it from my project for Pico W. It requires WiFi network nearby. You can get actual time from NTP server and use it in your code. It is untested, just as an example...

main.py

Code:

import timeimport networkimport uasyncio as asynciofrom machine import RTC# Configure your WiFi SSID and passwordssid = 'your ssid'         #Your network namepassword = 'your password' #Your WiFi passwordrtc=machine.RTC()tm = [2024, 1, 1, 23, 59, 59, 0, 0] # year, month, day, hour, minute, second, milicesond,check_interval_sec = 0.25# Function: get time from NTP Serverdef getTimeNTP():    global tm    try:        NTP_DELTA = 2208988800        NTP_QUERY = bytearray(48)        NTP_QUERY[0] = 0x1B        addr = socket.getaddrinfo(NTP_HOST, 123)[0][-1]        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)        try:            s.settimeout(1)            res = s.sendto(NTP_QUERY, addr)            msg = s.recv(48)        finally:            s.close()        ntp_time = struct.unpack("!I", msg[40:44])[0]        return time.gmtime(ntp_time - NTP_DELTA + GMT_OFFSET)    except:        #print('TimeNTP NOT Available')        return tm#-------------------------------------------------------------------------------# Function: copy time to PI pico´s RTCdef setTimeRTC():    global tm    tm = getTimeNTP()    rtc.datetime((tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0))#-------------------------------------------------------------------------------# Get time-date whenever you need itdef get_time():    timestamp=rtc.datetime()    year = timestamp[0]    month = timestamp[1]    day = timestamp[2]    hour = timestamp[4]    minute = timestamp[5]    second = timestamp[6]    return year, month, day, hour, minute, second#-------------------------------------------------------------------------------        async def connect_to_wifi():    wlan.active(True)    #wlan.config(pm = 0xa11140)  # Diable powersave mode        # You have to put here correct IP address for your case!!!!!!!    wlan.ifconfig(('192.168.x.xxx', '255.255.255.0', '192.168.x.x', '8.8.8.8'))    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:        blink_led(0.1, 10)        raise RuntimeError('WiFi connection failed')    else:        blink_led(0.5, 2)        #print('connected')        status = wlan.ifconfig()        print('ip = ' + status[0])#-------------------------------------------------------------------------------async def serve_client(reader, writer):    global OUT_Buffer_temperature, OUT_Buffer_hours        aaa = ""    response = html % aaa    #print("Client connected")    request_line = await reader.readline()    #print("Request:", request_line)    # We are not interested in HTTP request headers, skip them    while await reader.readline() != b"\r\n":        pass        # find() valid garage-door commands within the request    request = str(request_line)    cmd_up = request.find('DOOR=UP')    cmd_down = request.find('DOOR=DOWN')    cmd_stop = request.find('DOOR=STOP')    cmd_get = request.find('DOOR=GET')    stateis = "" # Keeps track of the last command issued    stateis_1 = ""        # Carry out a command if it is found (found at index: 8)    if cmd_stop == 8:        stateis = str(OUT_Buffer_temperature)        stateis_1 = str(OUT_Buffer_hours)        control_door('stop')        response = html.replace("${DATA}", stateis);        response = response.replace("${LABELS}", stateis_1);            elif cmd_up == 8:        stateis = ": ODPRI-ZAPRI"        control_door('up')        response = html % stateis            elif cmd_get == 8:        b = ReadTemperature()        abc = preveri_vrata()        stateis = (": Temp.garaza = " + str(b) + " *C  :" + abc)         control_door('stop')        response = html % stateis            elif cmd_down == 8:        stateis = ": Get NTP"        #print(stateis)        control_door('down')        response = html % stateis        #response = html.replace("${DATA}", stateis);    #response = response.replace("${LABELS}", stateis_1);    #print(response)    writer.write('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')    writer.write(response)    await writer.drain()    await writer.wait_closed()#-------------------------------------------------------------------------------async def main():        #print('Connecting to WiFi...')    asyncio.create_task(connect_to_wifi())    #print('Setting up webserver...')    asyncio.create_task(asyncio.start_server(serve_client, "0.0.0.0", 80))        # Get TimeNTP & put it to pico's RTC...    setTimeRTC()    while True:        await asyncio.sleep(check_interval_sec)        ...        other code        ...#-------------------------------------------------------------------------------try:    #print('asyncio.run(main())')    asyncio.run(main())    finally:    asyncio.new_event_loop()

Statistics: Posted by California — Wed Apr 24, 2024 8:50 pm



Viewing all articles
Browse latest Browse all 5083

Trending Articles