517 views|1 replies

1

Posts

2

Resources
The OP
 

【Digi-Key Follow me Issue 2】Tasks 1~4 (Sub-task 1) [Copy link]

 This post was last edited by Li Liuyiyu on 2023-11-20 13:38

Hello everyone, I am very happy to participate in the 2nd Follow me event of Digi-Key Electronics. I have previously learned about and used C51 microcontrollers, some entry-level products of STM32, and ESP8266 of the ESP product line, all of which were written in C/C++. In this experiment, I tried to use CircuitPython to complete the task in the Adafruit ESP32-S3 TFT Feather used in this experiment. Since I had hardly used Phyhon for microcontroller development before, I encountered various problems in the process. When I had no idea, I read the examples of some big guys in the forum, gradually explored, and finally completed this experiment. I would like to thank all the big guys for their detailed explanations in the forum, and thank Digi-Key Electronics for providing the opportunity.

Part 1: Hardware introduction and overall experimental completion demonstration video

This video will introduce the hardware used in the activity and a brief description of the related tasks, including tasks 1 to 4 (subtask 1)

Part II: Mission Summary Report

In this section, I will introduce the code and related ideas used in each sub-task:
Task 1: Control the screen to display Chinese

In Task 1, you need to use a font file of 2.07MB. Of course, this is a relatively simple method but it takes up a lot of microcontroller resources. You can also add only the parts you need. The specific fonts will be shown in the code file in Part 3. In the experiment, you need to put the font file in the same directory as the program file. The program files of this task are all named code.py.
This is achieved by calling the adafruit_display_text and adafruit_bitmap_font external libraries, using the load_font code under bitmap_font in adafruit_bitmap_font to obtain the font. To display text, use the Label class of adafruit_display_text to create an instance, use the previously obtained font as a parameter, and finally use board.DISPLAY.show() to complete the text display.
The following is the relevant code used in Task 1. The code implements basic text display and loop display of text. It can customize the display position, size, and color of the text. The specific code is commented in the code.
import board
import terminalio
from adafruit_display_text import bitmap_label
from adafruit_bitmap_font import bitmap_font
import time

font = bitmap_font.load_font("Word_bank.pcf")

display = board.DISPLAY

color = {
        "black" : 0x000000,
        "white" : 0xFFFFFF,
        "red" : 0xFF0000,
        "green" : 0x00FF00,
        "blue" : 0x0000FF,
        "cyan" : 0x00FFFF,
        "magenta" : 0xFF00FF,
        "yellow" : 0xFFFF00,
        }#字体颜色配置

txtCollection = ["用户名:黎琉一御","Hello World!"]
#显示位
scaleCollection = [2,4]
#字体大小

text_area = bitmap_label.Label(font,color=color["white"])       #字体颜色
text_area.x = 0                                                 #初始X位置
text_area.y = 60                                               #初始Y位置
text_area.text = "任务一展示"
text_area.scale = 2
display.show(text_area)
time.sleep(2)
#基础显示

while True:
        text_area = bitmap_label.Label(font,color=color["blue"])       #字体颜色
        text_area.x = 0                                                 #初始X位置
        text_area.y = 60                                               #初始Y位置
        text_area.text = txtCollection[0]
        text_area.scale = scaleCollection[0]
        display.show(text_area)
        time.sleep(1)
        text_area = bitmap_label.Label(font,color=color["yellow"])       #字体颜色
        text_area.x = 0                                                 #初始X位置
        text_area.y = 60                                               #初始Y位置
        text_area.text = txtCollection[1]
        text_area.scale = scaleCollection[1]
        display.show(text_area)
        time.sleep(1)
#循环显示

Task 2: Use of network functions

For this development board, you only need to call the existing WiFi library to achieve WiFi connection. Due to the privacy protection restrictions of the mobile phone, the specific details about WiFi cannot be displayed. The following are some pictures of the implementation

After successfully connecting to Wi-Fi, the assigned IP address is displayed on the TFT screen.
The following is the relevant code used in Task 2. The code implements connecting to wifi and displaying the IP address. The specific code is commented
import board
import terminalio
import os
import wifi
from adafruit_display_text import bitmap_label
from adafruit_bitmap_font import bitmap_font
import time

font = bitmap_font.load_font("Word_bank.pcf")

display = board.DISPLAY

wifi.radio.connect('FTP_LI', 'interlinked')
#连接的wifi格式	wifi.radio.connect('wifi名称', '密码')				
adress = "IP地址" + str(wifi.radio.ipv4_address)

color = {
        "black" : 0x000000,
        "white" : 0xFFFFFF,
        "red" : 0xFF0000,
        "green" : 0x00FF00,
        "blue" : 0x0000FF,
        "cyan" : 0x00FFFF,
        "magenta" : 0xFF00FF,
        "yellow" : 0xFFFF00,
        }#字体颜色配置

text_area = bitmap_label.Label(font,color=color["white"])       #字体颜色
text_area.x = 0                                                 #初始X位置
text_area.y = 60                                               #初始Y位置
text_area.text = "任务二展示"
text_area.scale = 2
display.show(text_area)
time.sleep(2)

text_area = bitmap_label.Label(font,color=color["white"])       #字体颜色
text_area = bitmap_label.Label(font,text=adress)
text_area.scale = 2
text_area.x = 0
text_area.y = 60
display.show(text_area)

while True:
    pass

Task 3: Control WS2812B

In this experiment, in order to more intuitively display the control of WS2812B, the onboard Neopixel LED will be controlled by buttons.

By calling the adafruit_led_animation library file, which contains a variety of LED display effects, including color, display status, etc., in this experiment, the red, yellow, blue, and green flashing modes will be selected for display. The flashing and cycle display modes are realized through Blink(pixels, speed=0.5, color=BLACK) and ColorCycle(pixels, speed=0.5). Pixels corresponds to the controlled WS2812B, speed corresponds to the display time interval, and color corresponds to the displayed color. Because the ColorCycle mode will display the colors in a cycle, no color setting is performed.

For this development board, the boot button is used as the control button in this experiment. By calling the digitalio library, use DigitalInOut(board.BOOT0) to obtain the level change of the IO port corresponding to the boot button, and initialize the button to control the input mode with the direction attribute buttom.direction = Direction.INPUT, configure the pull attribute buttom.pull = Pull.UP to set it to pull-up mode, obtain the IO port level change through buttom.value, and judge the experimental function.

The following is the relevant code used in Task 3. The code implements the control of WS2812B through the boot button. The specific code is commented

import board
import time
import neopixel
from digitalio import DigitalInOut,Direction,Pull
from adafruit_led_animation.animation.blink import Blink
from adafruit_led_animation.animation.colorcycle import ColorCycle
from adafruit_led_animation.color import RED, YELLOW, BLUE, GREEN,BLACK

pixel_pin = board.NEOPIXEL
pixel_num = 1
pixels = neopixel.NeoPixel(pixel_pin, pixel_num, brightness=0.1, auto_write=False, pixel_order=neopixel.GRB)
#初始化像素灯

buttom = DigitalInOut(board.BOOT0)
buttom.direction = Direction.INPUT
buttom.pull = Pull.UP
#初始化BOOT0按键

#LED模式状态指示物
pixel_modeflag = 0
blink = Blink(pixels, speed=0.5, color=BLACK)
colorcycle = ColorCycle(pixels, speed=0.5)
print("LED ColorCycle")

while True:
    if not buttom.value: #监测按键
        pixel_modeflag = pixel_modeflag + 1
        if (pixel_modeflag % 5 == 1):
            blink = Blink(pixels, speed=0.2, color=RED)
            print("LED Blink in RED")
        elif (pixel_modeflag % 5 == 2):
            blink = Blink(pixels, speed=0.2, color=YELLOW)
            print("LED Blink in YELLOW")
        elif (pixel_modeflag % 5 == 3):
            blink = Blink(pixels, speed=0.2, color=BLUE)
            print("LED Blink in BLUE")
        elif (pixel_modeflag % 5 == 4):
            blink = Blink(pixels, speed=0.2, color=GREEN)
            print("LED Blink in GREEN")            
        elif (pixel_modeflag % 5 == 0):
            colorcycle = ColorCycle(pixels, speed=0.1)
            print("LED ColorCycle")
    else:
        pass
    time.sleep(0.2)
        
    if (pixel_modeflag % 5 == 0):
        colorcycle.animate()#循环显示配置输出
    else:
        blink.animate()#闪烁显示配置输出

Task 4: Sub-task 1: Calendar & Clock

In this experiment, data is obtained through networking, the perpetual calendar clock updated by the Internet is tested, and the local weather information is displayed.

Using the codes of Task 1 and Task 2 together, we will first output the data obtained from the Internet. In the data acquisition part, we need the local city code. In the third part, we prepare an excel file, which contains the city codes of all cities, so that you can search and organize the returned data. Some of the formats are as follows:

{'sysTime1': '20231118195118', 'sysTime2': '2023-11-18 19:51:18'}

{'time': '2023-11-18 19:31:20', 'date': '20231118', 'message': 'success Thanks to Upyun.com for providing CDN sponsorship',

'cityInfo' : {'updateTime': '14:46', 'citykey': '101071401', 'city': 'Huludao City', 'parent': 'Liaoning'},

'data' : {'wendu': '2', 'pm10': 27.0, 'quality': 'Excellent', 'shidu': '24%',

'forecast' :

[{'notice': 'May you have a mood brighter than the sun', 'sunrise': '06:47', 'week': 'Saturday', 'sunset': '16:37', 'low': 'Low temperature -8℃', 'ymd': '2023-11-18', 'date': '18', 'fl': 'Level 3', 'fx': 'West wind', 'high': 'High temperature 8℃', 'aqi': 29, 'type': 'Sunny'},

{'notice': 'May you have a mood brighter than the sun', 'sunrise': '06:48', 'week': 'Sunday', 'sunset': '16:36', 'low': 'Low temperature 3℃', 'ymd': '2023-11-19', 'date': '19', 'fl': 'Level 3', 'fx': 'North wind', 'high': 'High temperature 12℃', 'aqi': 23, 'type': 'Sunny'},

It is not difficult to see that this is a large dictionary with a large amount of data. It is classified according to the key values and displayed according to your needs.

In this experiment, Huludao, Liaoning Province is taken as an example to display the local location information, the corresponding time and air quality, weather conditions, maximum temperature, minimum temperature, and the corresponding notice.

After connecting to wifi, data is requested once per second. Due to data return and processing, real-time display cannot be achieved, but the display refresh can be improved by reducing the interval. In the connection part, if it cannot connect to wifi, information such as Wifi connect error will be output and try to reconnect

The following is the relevant code used in Task 4. The code implements a perpetual calendar clock updated via the Internet and displays local weather information. The specific details are commented in the code
import board
import os, wifi
import time
import ssl
import socketpool
import adafruit_requests

from adafruit_display_text import bitmap_label
from adafruit_bitmap_font import bitmap_font

JSON_TIME_URL = "http://quan.suning.com/getSysTime.do"
JSON_WEATHER_URL = "http://t.weather.sojson.com/api/weather/city/{}"
#请求获取JSON

#获取数据,返回str
def get_date():
    response = requests.get(JSON_TIME_URL)
    time_date = response.json()

    city_code = "101071401"#城市码
    url = JSON_WEATHER_URL.format(city_code)
    response = requests.get(url)
    city_date = response.json()   

    City_Name = city_date['cityInfo']['parent']+'省 '+city_date['cityInfo']['city']
    City_Weather = city_date['data']
    City_Forecast = City_Weather['forecast']
    CurrentTime = time_date['sysTime2'] + '  ' + City_Forecast[0]['week']
    TotalStr = City_Name
    TotalStr += "\n时间:" + CurrentTime
    TotalStr += "\n空气质量:" + City_Weather['quality']
    TotalStr += "\t天气状态:" + City_Forecast[0]['type']
    TotalStr += "\n最高温度:" + City_Forecast[0]['high'][2:]
    TotalStr += "\n最低温度:" + City_Forecast[0]['low'][2:]
    TotalStr += "\n寄语:" + City_Forecast[0]['notice'] 
    #print(type(TotalStr))
    return TotalStr

font = bitmap_font.load_font("Word_bank.pcf")
display = board.DISPLAY
color = {
        "black" : 0x000000,
        "white" : 0xFFFFFF,
        "red" : 0xFF0000,
        "green" : 0x00FF00,
        "blue" : 0x0000FF,
        "yellow" : 0xFFFF00,
        }
def screen_display(text):
    text_area = bitmap_label.Label(font,color=color["white"])
    text_area.scale = 1
    text_area.x = 0
    text_area.y = 5
    text_area.text = text
    display.show(text_area)
#显示屏显示初始化  

while not wifi.radio.connected:
    try:
        wifi.radio.connect('FTP_LI','interlinked')
    except ConnectionError as e:
        print("Wifi connect error:{},wait for retry".format(e))
    time.sleep(0.1)
#wifi连接

pool = socketpool.SocketPool(wifi.radio)
requests = adafruit_requests.Session(pool, ssl.create_default_context())


while True:       
    screen_display(get_date())
    time.sleep(1)

Part 3: Compilable and downloadable code

All the font files, related codes and related program files used in Tasks 1 to 4 (Sub-task 1) of this [Digi-Key Follow me Phase 2] have been packaged and uploaded. Here are two ways to download them.

Baidu network disk link:

链接已隐藏,如需查看请登录或者注册

Extraction code: h9hr
Download Center: Follow me Issue 2 Adafruit ESP32-S3 TFT Feather-Embedded Development Related Materials Download-EEWORLD Download Center

This post is from DigiKey Technology Zone

Latest reply

Thanks for the technical sharing provided by the host. I will collect and study it first and then express my personal opinion.   Details Published on 2023-11-23 19:00
 
 

725

Posts

4

Resources
2
 

Thanks for the technical sharing provided by the host. I will collect and study it first and then express my personal opinion.

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