519 views|1 replies

29

Posts

2

Resources
The OP
 

【Digi-Key Follow Me Issue 2】 Task 4: Sub-task 1: Calendar & Clock [Copy link]

 This post was last edited by knv on 2023-10-10 00:06

【Digi-Key Follow Me Issue 2】 Task 4: Sub-task 1: Calendar & Clock - Complete a perpetual calendar clock that can be updated via the Internet and display local weather information

0x0: Related APIs

This time, we use Amap to obtain regional information based on IP access.

Use Amap's API to get weather information based on region information

Use http://worldtimeapi.org/api/ip to get accurate time information

Create secrets.py

secrets = {
"ssid": "这是ssid",
"password": "这是密码",
"timezone": "Asia/Shanghai", # Checkhttp://worldtimeapi.org/timezones
"token":"高德api token"
}

0x1: Libraries used

Create a wifi link information file secrets.py

0x2: Writing code

import board
import wifi
import time
import ssl
import socketpool
import adafruit_requests
import displayio
import terminalio
import adafruit_imageload
from adafruit_display_text import label
import adafruit_bitmap_font.bitmap_font
import rtc
the_rtc = rtc.RTC()

After the basic library is imported, configure the WIFI connection

token = "高德API的token"
### connecte to a WiFi AP (AP name and password in secrets.py) ###
try:
    from secrets import secrets
except ImportError:
    print("WiFi secrets are kept in secrets.py, please add them there!")
    raise



print("Connecting to %s" % secrets["ssid"])
wifi.radio.connect(secrets["ssid"], secrets["password"])
print("Connected to %s!" % secrets["ssid"])

Get screen information and set screen direction

screen = board.DISPLAY

screen.rotation = 90

Set a background image

bitmap, palette = adafruit_imageload.load("/imgs/purple.bmp",bitmap=displayio.Bitmap,palette=displayio.Palette)

# Create a TileGrid to hold the bitmap

tile_grid = displayio.TileGrid(bitmap, pixel_shader=palette,tile_width=160, tile_height=240,# pixels number
                                         width=1, height=1) # tiles number

Create some display information

FONT = adafruit_bitmap_font.bitmap_font.load_font("mfyh-16.bdf")

arealabel = label.Label(FONT, x=0, y=32, text="北京市", scale=1, color=(255,255,255))

wtlabel = label.Label(FONT, x=0, y=62, text="晴", scale=1, color=(255,255,255))

wdlabel = label.Label(FONT, x=0, y=92, text="温度:", scale=1, color=(255,255,255))

sdlabel = label.Label(FONT, x=0, y=122, text="湿度:", scale=1, color=(255,255,255))

yearlabel = label.Label(FONT, x=0, y=152, text="时间:", scale=1, color=(255,255,255))

monthlabel = label.Label(FONT, x=0, y=182, text="", scale=1, color=(255,255,255))

daylabel = label.Label(FONT, x=0, y=212, text="", scale=1, color=(255,255,255))

# Create a Group to hold the TileGrid

group = displayio.Group()

# Add the TileGrid to the Group

group.append(tile_grid)

group.append(arealabel)

group.append(wtlabel)

group.append(wdlabel)

group.append(sdlabel)

group.append(yearlabel)

group.append(monthlabel)

group.append(daylabel)

screen.show(group)

tile_grid[0] = 0

time.sleep(1.0)

Print WIFI information and create SOKCET connection pool

print("IP addr:", wifi.radio.ipv4_address)

response = None

pool = socketpool.SocketPool(wifi.radio)

# 建立连接

session = adafruit_requests.Session(pool, ssl.create_default_context())

Use Gaode API to obtain the region code of the IP

while True:
    response = session.get("https://restapi.amap.com/v3/ip?key="+token)
    data = response.json()
    #print("data:",data["adcode"])
    adcode = data["adcode"]
    time.sleep(1)
    break

Use worldtimeapi to get local time

while True:
    response = session.get("http://worldtimeapi.org/api/ip")
    json = response.json()
    current_time = json["datetime"]
    the_date, the_time = current_time.split("T")
    year, month, mday = [int(x) for x in the_date.split("-")]
    the_time = the_time.split(".")[0]
    hours, minutes, seconds = [int(x) for x in the_time.split(":")]
    # We can also fill in these extra nice things
    year_day = json["day_of_year"]
    week_day = json["day_of_week"]
    # Daylight Saving Time (夏令时)?
    is_dst = json["dst"]
    now = time.struct_time(
        (year, month, mday, hours, minutes, seconds+1, week_day, year_day, is_dst) )
    the_rtc.datetime = now
    time.sleep(1)
    break
loopdata = 600

Use Amap API to refresh data information regularly

while True:
    #yearlabel.text = "时间:"+str(the_rtc.datetime.tm_year)
    monthlabel.text = ""+str(the_rtc.datetime.tm_mon)+"-"+str(the_rtc.datetime.tm_mday)+""
    daylabel.text = "" + str(the_rtc.datetime.tm_hour) + ":" + str(the_rtc.datetime.tm_min) + ":"+str(the_rtc.datetime.tm_sec)+""
    try:
        if loopdata==600:
            response = session.get("https://restapi.amap.com/v3/weather/weatherInfo?key="+token+"&city="+adcode)
            data = response.json()
            #print("data:",data["adcode"])
            wd = data["lives"][0]["temperature_float"]
            sd = data["lives"][0]["humidity_float"]

            wdlabel.text ="温度: "+ wd+"°"
            sdlabel.text = "湿度: "+sd+"%"
            arealabel.text =  data["lives"][0]["province"]
            wtlabel.text =  data["lives"][0]["weather"]
            loopdata=0
        else:
            loopdata = loopdata +1
        time.sleep(1)
    except:
        pass

The effect is as follows:

QQ视频20231009223448

Video link:

https://training.eeworld.com.cn/video/37981

The download links for source code and libraries are as follows:

https://download.eeworld.com.cn/detail/knv/629533

After studying the second phase of Digi-Key Follow Me, I learned more modern MCU development skills. Using Python can develop programs and implement projects more quickly.

This post is from DigiKey Technology Zone

Latest reply

After studying the second phase of Digi-Key Follow Me, I learned more modern MCU development skills. Using Python can develop programs and implement projects more quickly. Congratulations on completing the task, and you have also learned something new.   Details Published on 2023-10-14 13:17
 
 

6827

Posts

11

Resources
2
 

After studying the second phase of Digi-Key Follow Me, I learned more modern MCU development skills. Using Python can develop programs and implement projects more quickly.

Congratulations on completing the task, and you have also learned something new.

This post is from DigiKey Technology Zone
 
 
 

Guess Your Favourite
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