625 views|1 replies

29

Posts

2

Resources
The OP
 

【Digi-Key Follow me Issue 2】Task Summary [Copy link]

 This post was last edited by knv on 2023-10-10 16:45

1: Post Summary

【Digi-Jet Follow me Issue 2】 Task 1: Control the screen to display Chinese https://en.eeworld.com/bbs/thread-1258723-1-1.html

【Digi-Key Electronics Follow me Issue 2】 Task 2: Use of network functions https://en.eeworld.com/bbs/thread-1258724-1-1.html

【Digi-Key Electronics Follow me Issue 2】 Task 3: Control WS2812B https://en.eeworld.com/bbs/thread-1258725-1-1.html

【Digi-Key Electronics Follow me Issue 2】 Task 4: Subtask 1: Calendar & Clock https://en.eeworld.com/bbs/thread-1258726-1-1.html

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

2: Task 1: Control the screen to display Chinese

Finally waited for the board to be shipped, SF Express free shipping, the speed is very fast

This small board is packed in a big box, it's so luxurious haha

After receiving it, I powered on and started it. The demo program loaded correctly. I was lucky.

0x0: Flash the device

The board is only in demo state, you need to flash it first

Download the official flash tool from Espressif

Download the bin file corresponding to the board from circuitpython.org and flash it

Using official tools

Configure the firmware address, select the corresponding com interface, and configure the baud rate to 115200

Click “erase”

After waiting for the clearing to complete, click "Start"

After the flashing is completed, click the reset button and the following interface will be displayed. The firmware has been flashed.

The computer successfully displays the USB drive

0x1: Preparation before displaying Chinese

To display Chinese, you need to create a font file first.

I use the software "FontSmaller 2.0.exe" to simplify the font file, and then use "u8g2_fontmaker" to create the font file.

Proceed as follows:

  1. : Open the FontSmaller software and select a font file
  2. Enter the characters you want to display
  3. Click OK to generate a simplified font

    preview effect
  4. Use batch generation

The generated BDF file is very small

Copy the font file to the development board

0x2: Display Chinese

After watching the live broadcast, I learned that if I want to use Adafruit ESP32-S3 TFT Feather to display Chinese, I also need to use an adafruit_display_text library, so I downloaded the library to the lib of the development board.

The code is also very simple

import board

import displayio

from adafruit_display_text import label

import adafruit_bitmap_font.bitmap_font

display = board.DISPLAY

board.DISPLAY.brightness = 1

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

text_group = displayio.Group()

text_area = label.Label(font, text="北京市房山区晴天", color=(255,255,255))

text_area.x = 0

text_area.y = 20

text_group.append(text_area)

display.show(text_group)

display effect:

Three: Task 2: Use of network functions

0x0: Create a secrets.py file to save wifi information

Contents below

secrets = {

"ssid": "This is the ssid",

"password": "This is the password",

"timezone": "Asia/Shanghai", # Check http://worldtimeapi.org/timezones

}

0x1: Connect to wifi

The WiFi connection code is as follows, where WiFi.radio.connect is used to connect to WiFi.

import board
import displayio
from adafruit_display_text import label
import adafruit_bitmap_font.bitmap_font

import wifi
import time
import ssl
import socketpool
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"])

display = board.DISPLAY
board.DISPLAY.brightness = 1
font = adafruit_bitmap_font.bitmap_font.load_font("mfyh-16.bdf")
text_group = displayio.Group()
text_area = label.Label(font, color=(255,255,255))
text_area.text=str(wifi.radio.ipv4_address)
text_area.x = 0
text_area.y = 20
text_group.append(text_area)

display.show(text_group)

The results are as follows:

0x1: Create an AP. The key point is to use the wifi.radio.start_ap function to create it successfully. It is very simple.

code show as below:

import board
import digitalio
import displayio
from adafruit_display_text import label, wrap_text_to_lines
from adafruit_bitmap_font import bitmap_font

import wifi
import os
import time

display = board.DISPLAY
board.DISPLAY.brightness = 0.35
board.DISPLAY.rotation = 0

font = bitmap_font.load_font("font/DingTalk_ncn_60.pcf")
color = 0xffffff

text_change = 0

text_group = displayio.Group()
text_area = label.Label(font, text="test", color=color)
text_area.x = 2
text_area.y = 50
text_area.line_spacing = 0.8
text_area.scale = 1
wifi.radio.start_ap('wifitest', '12345678')
text_area.text="running"
text_group.append(text_area)
display.show(text_group)
while True:
    time.sleep(2)

operation result:

Task 3: Control WS2812B

0x0: Prepare the board connection. Import the library adafruit_ws2801.py for controlling the RGB light

The RGB lights of the board are

board.NEOPIXEL

Just use the neopixel library to control the device with RGB

To switch the light color, first create a color list and define the color RGB value

colors = [(0x00, 0x00, 0x00), # black
(0xFF, 0x00, 0x00), # red
(0x00, 0xFF, 0x00), # green
(0x00, 0x00, 0xFF), # blue
(0xFF, 0xFF, 0xFF) ] # white

Create a loop to listen for key events. If a key is pressed, the color is increased by 1, and the color of color is used. This reduces the size of the code and makes the program logic clearer.

The screen also displays the corresponding color text, which is similar to the previous display of Chinese code, so I will not repeat it here.

0x1: The code is as follows

import time
import board
import neopixel
import digitalio
from adafruit_display_text import bitmap_label
from adafruit_bitmap_font import bitmap_font

# Load the font
font = bitmap_font.load_font("font/DingTalk_ncn_60.pcf")

# Define colors
colors = [(0x00, 0x00, 0x00),  # black
          (0xFF, 0x00, 0x00),  # red
          (0x00, 0xFF, 0x00),  # green
          (0x00, 0x00, 0xFF),  # blue
          (0xFF, 0xFF, 0xFF)]  # white

# Initialize NeoPixel
pixel = neopixel.NeoPixel(board.NEOPIXEL, 1)
pixel.brightness = 0.5

# Initialize the button
button = digitalio.DigitalInOut(board.BUTTON)
button.switch_to_input(pull=digitalio.Pull.UP)

# Initialize text label
text_area = bitmap_label.Label(font, scale=1)
text_area.x = 0
text_area.y = 60

current_color_index = -1

while True:
    # Read the button state
    button_state = not button.value
    
    if button_state:
        # Cycle through colors
        current_color_index = (current_color_index + 1) % len(colors)
        pixel.fill(colors[current_color_index])
        
        # Set the text and color
        text2 = ["black", "red", "green", "blue", "white"][current_color_index]
        text_area.text = text2
        text_area.color = colors[current_color_index]
        board.DISPLAY.show(text_area)
    
    time.sleep(0.1)

The display effect is as follows:

QQ视频20231009222545

Five: 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 participating in the second phase of Digi-Key's Follow Me program, I have mastered more modern MCU development skills. Using the Python programming language, I can develop programs more quickly and implement projects smoothly. This learning experience has benefited me a lot and has provided important help for my career development and skill improvement.

This post is from DigiKey Technology Zone

Latest reply

Using wifi.radio.start_ap function is the key point   Details Published on 2023-10-11 07:41
 
 

1663

Posts

0

Resources
2
 

Using wifi.radio.start_ap function is the key point

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