- 2023-11-26
-
加入了学习《【得捷电子Follow me第3期】智能家居之环境监测应用》,观看 智能家居之环境监测
- 2023-11-03
-
发表了主题帖:
【DigiKey“智造万物,快乐不停”创意大赛】多功能终端-准备固件
我使用的是esp32-s3 N16R2的模块,采用circuitpython作为开发基础,因此准备按照官方仓库指导编译tinyuf2和cpy固件.
克隆https://github.com/adafruit/circuitpython和https://github.com/adafruit/tinyuf2这两个仓库,然后按照说明一路安装,
接着复制类似的开发板文件,修改后即可进行编译,还是很容易的。
附件是我编译好的固件
- 2023-10-31
-
回复了主题帖:
电子书《数学之美》第2版
л
- 2023-10-20
-
加入了学习《【得捷电子Follow me第2期】 ESP32-S3 TFT 为智能物联赋能》,观看 得捷电子Follow me第2期】 ESP32-S3 TFT 赋能智能物联
- 2023-10-19
-
加入了学习《【得捷电子Follow me第2期】+ ESP32-S3 TFT 为智能物联赋能》,观看 【得捷电子Follow me第2期】+ ESP32-S3 TFT 为智能物联赋能
- 2023-10-09
-
发表了主题帖:
【得捷电子Follow me第2期】任务提交
非常高兴能继续参与到第二期的followme活动中,本次活动我体会到了circuitpython的开发便捷性,同时终于能亲自动手练习机器识别,按照现有例程进行实践一遍,收获颇丰,虽然还有很多不懂的地方,但总算迈出了第一步。
我使用了两块开发板,Adafruit ESP32-S3 TFT Feather和xiao ble sense(自带六轴传感器,省去接线烦恼)。
根据楚大佬的教学视频,我试着生成了中文字体,感谢大佬。
任务1:控制屏幕显示中文(必做任务)
任务主要用到了displayio、text、font等模块和库,官方都有现成的提供,只需调用即可
'''
任务1:控制屏幕显示中文(必做任务)
完成屏幕的控制,并且能显示中文
'''
import displayio
import board
from adafruit_bitmap_font import bitmap_font
from adafruit_display_text import label
import time
display = board.DISPLAY
display.show(None)
font_file = "font/Fontquan-XinYiGuanHeiTi-Regular.pcf"
font = bitmap_font.load_font(font_file)
hanzi = label.Label(font, color=0xff22ff, scale=1)
hanzi.anchor_point = (0.5, 0.5)
hanzi.anchored_position = (display.width//2, display.height//2)
hanzi.text = "Follow me 第2期\n与得捷电子一起解锁开发板超能力!"
main_group = displayio.Group()
main_group.append(hanzi)
display.show(main_group)
n=0
while True :
n=(n+255) & 0xffffff
hanzi.color = n
time.sleep(0.05)
# print(n)
任务2:网络功能使用(必做任务)
主要使用了wifi模块,从setting.toml读取wifi的ssid和pwd,然后连接路由器,最后切换到ap模式
'''
任务2:网络功能使用(必做任务)
完成网络功能的使用,能够创建热点和连接到WiFi
'''
import wifi,time,os
import displayio
import board
from adafruit_bitmap_font import bitmap_font
from adafruit_display_text import label
import time
display = board.DISPLAY
display.show(None)
font_file = "font/Fontquan-XinYiGuanHeiTi-Regular.pcf"
font = bitmap_font.load_font(font_file)
hanzi = label.Label(font, color=0xff22ff, scale=1)
hanzi.anchor_point = (0.5, 0.5)
hanzi.anchored_position = (display.width//2, display.height//2)
hanzi.text = "连接wifi中"
main_group = displayio.Group()
main_group.append(hanzi)
display.show(main_group)
while not wifi.radio.connected:
try:
wifi.radio.connect(os.getenv("WIFI_SSID"), os.getenv("WIFI_PASSWORD"))
except Exception as ex:
print(ex)
time.sleep(0.5)
print('.')
print(f"My IP address: {wifi.radio.ipv4_address}")
hanzi.text = f"已连接 WiFi\n我的IP地址: {wifi.radio.ipv4_address}"
wifi.radio.stop_station()
time.sleep(1.0)
hanzi.text = "关闭station模式\n开启AP模式"
wifi.radio.start_ap("ap")
time.sleep(1.0)
hanzi.text = "已开启AP模式\n请连接"
任务3:控制WS2812B(必做任务)
主要使用到内置的neopixel模块,按下按键,屏幕和灯同时切换颜色
'''
**任务3:控制WS2812B(必做任务)**
使用按键控制板载Neopixel LED的显示和颜色切换
'''
import displayio
import board
from adafruit_bitmap_font import bitmap_font
from adafruit_display_text import label
from adafruit_display_shapes.rect import Rect
import time
import keypad
import neopixel
import digitalio
GREEN = 0x00ff00
RED = 0xff0000
BLUE = 0x0000ff
YELLOW = 0xffff00
color = [GREEN,RED,BLUE,YELLOW]
power = digitalio.DigitalInOut(board.NEOPIXEL_POWER)
power.direction = digitalio.Direction.OUTPUT
power.value = True
pixel = neopixel.NeoPixel(board.NEOPIXEL,1)
pixel.brightness = 0.5
pixel.fill(color[0])
display = board.DISPLAY
display.show(None)
font_file = "font/Fontquan-XinYiGuanHeiTi-Regular.pcf"
font = bitmap_font.load_font(font_file)
background = Rect(0,0,display.width-1,display.height-1,fill = color[0])
hanzi = label.Label(font, color=0x000000, scale=1)
hanzi.anchor_point = (0.5, 0.5)
hanzi.anchored_position = (display.width//2, display.height//2)
hanzi.text = "Follow me 第2期\n与得捷电子一起解锁开发板超能力!"
main_group = displayio.Group()
main_group.append(background)
main_group.append(hanzi)
display.show(main_group)
keys = keypad.Keys((board.BUTTON,), value_when_pressed=False, pull = True)
event = keypad.Event()
def getkey():
if keys.events.get_into(event):
if event.pressed:
# print(event)
return event.key_number
if event.released:
return event.key_number+10
# print(event)
pass
return -1
i=0
while True:
time.sleep(0.1)
key = getkey()
if key == 0:
i=(i+1 )%4
background.fill = color[i]
pixel.fill(color[i])
任务4:■ 分任务1:日历&时钟——完成一个可通过互联网更新的万年历时钟,并显示当地的天气信息
这时一个对前面任务的一个综合应用,需要用到displayio、wifi、socketpool等模块,使用wifi进行时间同步,从心知天气获取天气信息并更新到屏幕上
'''
**分任务1:日历&时钟**——
完成一个可通过互联网更新的万年历时钟,并显示当地的天气信息
'''
import wifi
import socketpool
import os , gc
import rtc
import time
import board
from adafruit_display_text import label
from adafruit_display_text import bitmap_label
import adafruit_ntp
import displayio
import terminalio
import adafruit_requests
import ssl
import adafruit_imageload
display = board.DISPLAY
display.show(None)
# if not wifi.Radio.connected:
print(f"Connecting to \r\n[ {os.getenv('WIFI_SSID')} ]")
while not wifi.radio.connected:
try:
wifi.radio.connect(os.getenv("WIFI_SSID"), os.getenv("WIFI_PASSWORD"))
except Exception as ex:
print(ex)
time.sleep(0.5)
print('.')
print(f"My IP address: {wifi.radio.ipv4_address}")
TIME_API = "http://worldtimeapi.org/api/ip"
pool = socketpool.SocketPool(wifi.radio)
ntp = adafruit_ntp.NTP(pool, tz_offset=8, server = "ntp1.aliyun.com")
try:
rtc.RTC().datetime = ntp.datetime
except Exception as e:
print(e)
pass
time_now = time.localtime()
print(time_now)
requests = adafruit_requests.Session(pool, ssl.create_default_context())
WEATHERKEY = os.getenv("WEATHER_KEY")
if WEATHERKEY =="":
WEATHERKEY = 'ctpe2272nswh94og'
LOCATION = os.getenv("LOCATION")
if LOCATION=="":
LOCATION = 'sanya'
UNITS = "c"
LANGUAGE = 'en'
print("Getting weather for {}".format(LOCATION))
# Set up the URL for fetching weather data
DATA_SOURCE = (
"http://api.seniverse.com/v3/weather/now.json?"
+ "key="
+ WEATHERKEY
+ "&location="
+ LOCATION
+ "&language="
+ LANGUAGE
+ "&unit="
+ UNITS
)
# Define time interval between requests
time_interval = 1800 # set the time interval to 30 minutes
# Set up display a default image
#image, 8bit png
image, palette = adafruit_imageload.load("/images/weather/icons8-sunny-64_.png")
# Set the transparency index color to be hidden
palette.make_transparent(0)
tile_grid = displayio.TileGrid(image,pixel_shader = palette)
tile_grid.x = display.width // 2 - tile_grid.tile_width // 2-10
tile_grid.y = display.height // 2 - tile_grid.tile_height // 2
display.show(None)
main_group = displayio.Group()
from adafruit_bitmap_font import bitmap_font
font_file = "font/LeagueSpartan-Bold-16.bdf"
font = bitmap_font.load_font(font_file)
# font = terminalio.FONT
# label
hour_label = label.Label(terminalio.FONT, color=0x00ff00, scale=6)
hour_label.anchor_point = (1.0, 0.0)
hour_label.anchored_position = (display.width-1, 0)
hour_label.text = "{:0>2d}".format(time_now.tm_hour)
minute_label = label.Label(terminalio.FONT, color=0x00ffff, scale=6)
minute_label.anchor_point = (1.0, 0.0)
minute_label.anchored_position = (display.width-1, 64)
minute_label.text = "{:0>2d}".format(time_now.tm_min)
main_group.append(hour_label)
main_group.append(minute_label)
# main_group.append(gc_label)
WEEK_COLOR_NOW = 0xCCCCCC
WEEK_COLOR_NOTNOW=0x444444
week_id = time_now.tm_wday
week_label=[]
weeks = ("MON","TUE","WED","THU","FRI","SAT","SUN")
for i in range(7):
wlabel = label.Label(font, color=WEEK_COLOR_NOTNOW, scale=1)
wlabel.anchor_point = (0.0, 0.0)
wlabel.anchored_position = (0, i*19)
wlabel.text = f"{weeks[i]}"
week_label.append(wlabel)
main_group.append(wlabel)
week_label[week_id].color = WEEK_COLOR_NOW
main_group.append(tile_grid)
# Create label for displaying temperature data
text_area = bitmap_label.Label(terminalio.FONT, scale=2)
text_area.anchor_point = (0.5, 0.5)
text_area.anchored_position = (display.width // 2-10, display.height // 2)
main_group.append(text_area)
display.show(main_group)
now = time.monotonic()
old = now
# Define function to get the appropriate weather icon
def get_weather_condition_icon(weather_condition):
if "cloud" in weather_condition.lower():
return "/images/weather/icons8-cloudy-64_.png"
elif "rain" in weather_condition.lower():
return "/images/weather/icons8-rain-64_.png"
elif "snow" in weather_condition.lower():
return "/images/weather/icons8-snowy-64_.png"
elif "clear" in weather_condition.lower():
return "/images/weather/icons8-sunny-64_.png"
else:
return "/images/weather/icons8-sunny-64_.png"
# Define function to update the background image based on weather conditions
def set_background(weather_condition, background_tile_grid):
bitmap_path = get_weather_condition_icon(weather_condition)
image, palette = adafruit_imageload.load(bitmap_path)
palette.make_transparent(0)
background_tile_grid.bitmap = image
background_tile_grid.pixel_shader = palette
def get_weather():
# Fetch weather data from OpenWeatherMap API
print("Fetching json from", DATA_SOURCE)
response = requests.get(DATA_SOURCE)
print(response.json())
# Extract temperature and weather condition data from API response
current_weather_condition = response.json()["results"][0]["now"]["text"]
current_temp = response.json()["results"][0]["now"]["temperature"]
print("Weather condition: ", current_weather_condition)
# Update label for displaying temperature data
text_area.text = "{}\n\n\n {} C".format(LOCATION, current_temp)
# Update background image
set_background(current_weather_condition, tile_grid)
get_weather()
old_w = time.monotonic()
while True:
now = time.monotonic()
if (now-old) >= 10.0:
old = time.monotonic()
time_now = time.localtime()
gc.collect()
hour_label.text = "{:0>2d}".format(time_now.tm_hour)
minute_label.text = "{:0>2d}".format( time_now.tm_min)
if time_now.tm_wday != week_id:
week_label[week_id].color = WEEK_COLOR_NOTNOW
week_label[time_now.tm_wday].color = WEEK_COLOR_NOW
weekid = time_now.tm_wday
if (now-old_w) >= time_interval:
old_w = time.monotonic()
get_weather()
gc.collect()
time.sleep(0.2)
任务4:■ 分任务5:AI功能应用——结合运动传感器,完成手势识别功能,至少要识别三种手势(如水平左右、前后、垂直上下、水平画圈、垂直画圈,或者更复杂手势
本次任务,选用了xiao ble sense开发板,此板自带6轴传感器,非常方便进行手势识别的开发,省去接线的烦恼,主要使用arduino进行开发,使用了tinyml进行动作的识别。
本次代码主要是基于原来的例程进行实践,作为学习使用。原本只有两个动作,我修改成了其他的三个动作。
采集到数据后,在上位机进行训练,获得模型文件,然后再编译进开发板,串口输出识别的结果。
在过程中,主要是提供动作的训练数据,分别保存到csv文件,并分别命名。
在classifier中,定义手势即可
// array to map gesture index to a name
const char* GESTURES[] = {
"circle",
"h2left",
"h2right"
};
- 2023-10-04
-
加入了学习《Digi-Key: Follow Me 系列(2) 直播回放》,观看 Adafruit ESP32-S3 TFT Feather开发板使用入门
- 2023-10-02
-
加入了学习《Follow me第2期》,观看 得捷电子Follow me第2期任务视频
-
回复了主题帖:
【DigiKey“智造万物,快乐不停”创意大赛】开箱帖
秦天qintian0303 发表于 2023-10-1 20:24
期待优秀作品,楼主是有想法的,搞了这么多esp32
esp32是个好东西
- 2023-09-30
-
回复了主题帖:
【DigiKey“智造万物,快乐不停”创意大赛】开箱帖
tagetage 发表于 2023-9-30 17:57
屏幕挺好,什么规格的????
2.7" 400X240 黑白点阵
-
回复了主题帖:
【DigiKey“智造万物,快乐不停”创意大赛】开箱帖
dql2016 发表于 2023-9-30 15:11
求得捷元件号
LS027B7DH01A
-
回复了主题帖:
【DigiKey“智造万物,快乐不停”创意大赛】开箱帖
dql2016 2023-9-30 14:15
yes
-
发表了主题帖:
【DigiKey“智造万物,快乐不停”创意大赛】开箱帖
经过十多天,终于到货了,赶紧开个箱,包装还是一如既往的严实,尤其是那块屏幕。
esp32的那模块pcb有点偏蓝的效果,很漂亮。
主要物料基本都已买到。
项目中的键盘只能从咸鱼搞了。
后期打板要靠纯手工贴片了。
- 2023-07-17
-
回复了主题帖:
CircuitPython应用程序菜单启动器
都是大佬啊
- 2023-06-21
-
发表了主题帖:
【得捷电子Follow me第1期】+ 小猫相框
本帖最后由 qwert1213131 于 2023-6-21 20:08 编辑
[localvideo]4647dcdb786f4d792a245e668db040f1[/localvideo]
项目描述
本项目主要基于树莓派pico w开发板,板子支持wifi连接,由丰富的资源,可以使用micropython语言进行开发。
micropython内置了很多模块,非常方便调用。
项目主要是从网络获取随机的小猫图片,并解析显示到彩屏上。
在http://placekitten.com网站有很多各种尺寸的小猫图片,我们可以按照类似 http://placekitten.com/200/300 或http://placekitten.com/g/200/300这样的格式来显示宽200、高300的图片
实际在电脑上打开上面的网址,会发现图片是jpg格式存储的。因此我们还需要一个jpeg解析库来获取真实的像素数据,方便我们在屏幕上画点。
为了让屏幕显示不同的图片,需要调整长宽值,来获取不同的尺寸,做到图片变化的效果。
本项目主要用到了network、urequests、random、spi、time、gc等内置模块,还用到了大神们已经写好的JPEGdecoder和st7789py库。
由于rp2040的ram有限,为了防止读取网站图片和解析图片的失败,图片的尺寸限制在100x100左右。
目前所用的彩屏是1.3寸 240x240分辨率的,因此对获取到的图片做了放大处理。
主要代码详解
初始化彩屏,使用硬件spi
from machine import Pin,SPI
import st7789py as st7789
spi = SPI(0, baudrate=20_000_000, polarity=1, phase=1, bits=8, sck=Pin(6), mosi=Pin(7), miso=Pin(4))
tft = st7789.ST7789(
spi,
240,
240,
reset=Pin(9, Pin.OUT),
cs=Pin(5, Pin.OUT),
dc=Pin(8, Pin.OUT),
backlight=Pin(13, Pin.OUT),
rotation=0)
tft.fill(st7789.BLACK) # clear screen
通过network模块,连接wifi
import network
import time
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect('ssid','pass')
while not wlan.isconnected() and wlan.status()>=0:
print("Waiting to connect:")
time.sleep(1)
print(wlan.ifconfig())
通过urequests模块,访问网站,高度由random模块生成
import urequests
import random
html = "http://placekitten.com/{0}/{1}"
WIDTH=100
HEIGHT = 100+random.randint(0,10)
html = html.format(WIDTH,HEIGHT)
print(html)
r = urequests.get(html)
# print(r)
# print(r.content) # 返回响应的内容
将获取到的内容解析出来,图片质量目前设置的是4,会有一些质量损失
from JPEGdecoder import jpeg
jpeg(r.content,4,callback=draw ).render(10, (120-HEIGHT)>>1)
print("T:%d" % time.ticks_ms())
print(gc.mem_free())
解析并显示的过程中使用了回调函数draw
def rgb24_to_rgb565(color24):
r = (color24>>16) &0xff
g = (color24>>8) &0xff
b = (color24>>0) &0xff
r = (r >> 3) & 0x1F
g = (g >> 2) & 0x3F
b = (b >> 3) & 0x1F
return (r << 11) | (g << 5) | b
def draw(x,y,color):
# tft.pixel(x,y,rgb24_to_rgb565(color))
tft.rect(x*2,y*2,2,2,rgb24_to_rgb565(color))
print("T:%d" % time.ticks_ms())
最终我们就得到了小猫图片
任务
任务1:熟悉micropython的基本语法
向Raspberry Pi Pico w开发板烧写固件
在插入usb之前,按住BOOTSEL按钮,然后插入usb,就会出现一个盘符为RPI-RP2的U盘。 打开INFO_UF2.TXT,里面记录了板子的一些信息 点击U盘中的HTM文件,则会跳转到树莓派的网站,可以查看开发板的相关资源
点击上图的MicroPython则可以跳转到页面并下载相关固件
下载的固件是uf2格式的文件,将其拖入到u盘中,传输完成后,开发板就会自动重启
安装Mu软件,去官网下载安装即可
https://codewith.mu/en/
点击REPL按钮可看到如下信息
至此,开发板就已经可以正常使用micropython来开发了。
Hello World
想要通过串口打印hello world,则只要调用print函数即可,简直不要太简单了
print('Hello World')
1s间隔打印一次
import time
while True:
print('Hello World')
time.sleep(1.0)
使用for循环遍历列表
list_fruit_cn = ['苹果','桔子','樱桃','香蕉']
for fruit in list_fruit_cn:
print(fruit)
任务2:驱动外设
使用Pin模块来驱动led闪烁
from machine import Pin
import time
led = Pin('LED',Pin.OUT)
while True:
led.toggle()
time.sleep(0.5)
驱动OLED,使用I2C模块
使用ssd1306库https://github.com/stlehmann/micropython-ssd1306
from machine import Pin, I2C
i2c1 = I2C(1,sda=Pin(6), scl=Pin(7))
from ssd1306 import SSD1306_I2C
oled = SSD1306_I2C(128, 64, i2c1)
import time
oled.fill(1)
oled.show()
time.sleep(1.0)
oled.fill(0)
oled.show()
time.sleep(1.0)
oled.text('Hello', 0, 0)
oled.text('World', 0, 10)
oled.show()
驱动蜂鸣器
将gpio16引脚连接无源蜂鸣器,使用PWM模块来驱动发声
from machine import Pin, PWM
import utime
pwm0 = PWM(Pin(16)) # create PWM object from a pin
pwm0.freq() # get current frequency
pwm0.freq(1000) # set frequency
pwm0.duty_u16() # get current duty cycle, range 0-65535
pwm0.duty_u16(1000) # set duty cycle, range 0-65535
utime.sleep(1.0)
pwm0.deinit() # turn off PWM on the pin
任务3:同步网络时间
使用network模块来配置和连接网络
import network
import time
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect('wifi','pass')
while not wlan.isconnected() and wlan.status()>=0:
print("Waiting to connect:")
time.sleep(1)
print(wlan.ifconfig())
通过ntptime模块来获取网络时间
import ntptime
while True:
try:
print('获取时间中')
ntptime.host = 'ntp1.aliyun.com'
ntptime.settime()
print('成功获取')
break
except:
print('获取失败')
time.sleep(1)
while True:
print(time.localtime())
time.sleep(1.0)
任务4:实现定位功能
定位解析使用了大佬的库https://github.com/inmcm/micropyGPS
主要使用了UART模块,与Air530模块进行通信
from machine import Pin, I2C, UART
i2c1 = I2C(1,sda=Pin(6), scl=Pin(7))
from ssd1306 import SSD1306_I2C
oled = SSD1306_I2C(128, 64, i2c1)
import time
oled.fill(0)
oled.text('GPS', 0, 0)
oled.show()
time.sleep(1.0)
import hashlib
from micropyGPS import MicropyGPS
my_gps = MicropyGPS(local_offset=8)
uart0 = UART(0, baudrate=9600, tx=Pin(0), rx=Pin(1))
while True:
if uart0.any()>0:
# print(uart0.read(1))
state = my_gps.update(uart0.read(1).decode('utf-8'))
if state:
state = None
oled.fill(0)
lat_disp = my_gps.latitude_string()
oled.text(lat_disp,5,10)
lon_disp = my_gps.longitude_string()
oled.text(lon_disp,5,20)
date_disp = my_gps.date_string('s_mdy')
oled.text(date_disp,5,30)
time_disp = str(my_gps.timestamp[0]) +':'+str(my_gps.timestamp[1])+':'+str(my_gps.timestamp[2])
oled.text(time_disp,5,40)
oled.show()
活动总结
这个活动非常棒,体验了一把使用micropython开发的优势。以前做单片机开发,基本都是编译下载,非常耗时,调试也不是很方便。
最近迷上了micropython,还需要多做一些实践,进行一些项目开发,加深对micropython的使用度。
小猫相框,如果使用墨水屏就更好了,可惜手里没有,就先拿彩屏代替下了。实现思路上都是一样的。
非常感谢EEworld和得捷电子,非常不错的活动。
希望下次活动早日公布日程,我还想继续参加。
相关源代码
-
加入了学习《pico w 作业视频》,观看 天气预报
-
加入了学习《桌面天气预报小时钟——树莓派pico》,观看 桌面天气预报小时钟
- 2023-06-14
-
发表了主题帖:
【得捷电子Follow me第1期】+ Raspberry Pi Pico W 汇总
本帖最后由 qwert1213131 于 2023-6-14 20:32 编辑
[localvideo]a106c320c133fb1870f3cc9d04315e24[/localvideo]
以前搞开发的时候都是使用的C语言,采用编译、下载的方式,很耗时;而使用micropython作为开发单片机的语言,就可以简化开发流程,非常感谢得捷和eeworld论坛举办的活动。
任务1:熟悉micropython的基本语法
向Raspberry Pi Pico w开发板烧写固件
在插入usb之前,按住BOOTSEL按钮,然后插入usb,就会出现一个盘符为RPI-RP2的U盘。
打开INFO_UF2.TXT,里面记录了板子的一些信息
点击U盘中的HTM文件,则会跳转到树莓派的网站,可以查看开发板的相关资源
点击上图的MicroPython则可以跳转到页面并下载相关固件
下载的固件是uf2格式的文件,将其拖入到u盘中,传输完成后,开发板就会自动重启
安装Mu软件,去官网下载安装即可
https://codewith.mu/en/
点击REPL按钮可看到如下信息
至此,开发板就已经可以正常使用micropython来开发了。
Hello World
想要通过串口打印hello world,则只要调用print函数即可,简直不要太简单了
print('Hello World')
1s间隔打印一次
import time
while True:
print('Hello World')
time.sleep(1.0)
使用for循环遍历列表
list_fruit_cn = ['苹果','桔子','樱桃','香蕉']
for fruit in list_fruit_cn:
print(fruit)
任务2:驱动外设
使用Pin模块来驱动led闪烁
from machine import Pin
import time
led = Pin('LED',Pin.OUT)
while True:
led.toggle()
time.sleep(0.5)
驱动OLED,使用I2C模块
使用ssd1306库https://github.com/stlehmann/micropython-ssd1306
from machine import Pin, I2C
i2c1 = I2C(1,sda=Pin(6), scl=Pin(7))
from ssd1306 import SSD1306_I2C
oled = SSD1306_I2C(128, 64, i2c1)
import time
oled.fill(1)
oled.show()
time.sleep(1.0)
oled.fill(0)
oled.show()
time.sleep(1.0)
oled.text('Hello', 0, 0)
oled.text('World', 0, 10)
oled.show()
驱动蜂鸣器
将gpio16引脚连接无源蜂鸣器,使用PWM模块来驱动发声
from machine import Pin, PWM
import utime
pwm0 = PWM(Pin(16)) # create PWM object from a pin
pwm0.freq() # get current frequency
pwm0.freq(1000) # set frequency
pwm0.duty_u16() # get current duty cycle, range 0-65535
pwm0.duty_u16(1000) # set duty cycle, range 0-65535
utime.sleep(1.0)
pwm0.deinit() # turn off PWM on the pin
任务3:同步网络时间
使用network模块来配置和连接网络
import network
import time
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect('wifi','pass')
while not wlan.isconnected() and wlan.status()>=0:
print("Waiting to connect:")
time.sleep(1)
print(wlan.ifconfig())
通过ntptime模块来获取网络时间
import ntptime
while True:
try:
print('获取时间中')
ntptime.host = 'ntp1.aliyun.com'
ntptime.settime()
print('成功获取')
break
except:
print('获取失败')
time.sleep(1)
while True:
print(time.localtime())
time.sleep(1.0)
任务4:实现定位功能
定位解析使用了大佬的库https://github.com/inmcm/micropyGPS
主要使用了UART模块,与Air530模块进行通信
from machine import Pin, I2C, UART
i2c1 = I2C(1,sda=Pin(6), scl=Pin(7))
from ssd1306 import SSD1306_I2C
oled = SSD1306_I2C(128, 64, i2c1)
import time
oled.fill(0)
oled.text('GPS', 0, 0)
oled.show()
time.sleep(1.0)
import hashlib
from micropyGPS import MicropyGPS
my_gps = MicropyGPS(local_offset=8)
uart0 = UART(0, baudrate=9600, tx=Pin(0), rx=Pin(1))
while True:
if uart0.any()>0:
# print(uart0.read(1))
state = my_gps.update(uart0.read(1).decode('utf-8'))
if state:
state = None
oled.fill(0)
lat_disp = my_gps.latitude_string()
oled.text(lat_disp,5,10)
lon_disp = my_gps.longitude_string()
oled.text(lon_disp,5,20)
date_disp = my_gps.date_string('s_mdy')
oled.text(date_disp,5,30)
time_disp = str(my_gps.timestamp[0]) +':'+str(my_gps.timestamp[1])+':'+str(my_gps.timestamp[2])
oled.text(time_disp,5,40)
oled.show()
已经可以看到获取到的时间了,不过因为在房间的缘故,定位信息获取的比较慢,还得在窗户边;
不过在室外应该就能很容易获取位置信息了,可以在视频中看到
任务5:随机获取网站的小猫图片
这个项目主要是从http://placekitten.com/网站获取不同尺寸的小猫图片,并显示到TFT彩屏上,因此需要用到PICO W的很多功能模块
network负责wifi的连接
urequests负责网站资源的获取
random用来随机生成图片的尺寸
SPI用来与st7789的1.3寸屏幕通信
JPEGdecoder负责jpeg图片的解析
除此之外还需要用到外部驱动,JPEGdecoder.py和st7789py.py
# 在这里写上你的代码 :-)
import network
import time
import gc
import urequests
import random
from machine import Pin,SPI
#from machine import Pin,SoftSPI,
import st7789py as st7789
spi = SPI(0, baudrate=20_000_000, polarity=1, phase=1, bits=8, sck=Pin(6), mosi=Pin(7), miso=Pin(4))
# spi = SoftSPI(baudrate=30000000, polarity=1, sck=Pin(6), mosi=Pin(7), miso=Pin(4))
tft = st7789.ST7789(
spi,
240,
240,
reset=Pin(9, Pin.OUT),
cs=Pin(5, Pin.OUT),
dc=Pin(8, Pin.OUT),
backlight=Pin(13, Pin.OUT),
rotation=0)
tft.fill(st7789.BLACK) # clear screen
print(gc.mem_free())
gc.collect() # We're really gonna need that RAM!
print(gc.mem_free())
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect('ssid','pass')
while not wlan.isconnected() and wlan.status()>=0:
print("Waiting to connect:")
time.sleep(1)
print(wlan.ifconfig())
# 访问ip地址 api
html = "http://placekitten.com/{0}/{1}"
WIDTH=100
HEIGHT = 100+random.randint(0,10)
html = html.format(WIDTH,HEIGHT)
print(html)
r = urequests.get(html)
# print(r)
# print(r.content) # 返回响应的内容
print("size:%d" % len(r.content))
def rgb24_to_rgb565(color24):
r = (color24>>16) &0xff
g = (color24>>8) &0xff
b = (color24>>0) &0xff
r = (r >> 3) & 0x1F
g = (g >> 2) & 0x3F
b = (b >> 3) & 0x1F
return (r << 11) | (g << 5) | b
def draw(x,y,color):
# tft.pixel(x,y,rgb24_to_rgb565(color))
tft.rect(x*2,y*2,2,2,rgb24_to_rgb565(color))
print("T:%d" % time.ticks_ms())
from JPEGdecoder import jpeg
jpeg(r.content,4,callback=draw ).render(10, (120-HEIGHT)>>1)
print("T:%d" % time.ticks_ms())
print(gc.mem_free())
# It's mandatory to close response objects as soon as you finished
# working with them. On MicroPython platforms without full-fledged
# OS, not doing so may lead to resource leaks and malfunction.
r.close()
print(gc.mem_free())
gc.collect() # We're really gonna need that RAM!
print(gc.mem_free())
这就是网站获取到的图片,未来可以考虑将TFT屏幕换成大一些墨水屏,可以更新不同的猫猫图片,又省电有好玩。
再次感谢本次活动,终于体会到了用micropython开发的乐趣。
希望第二期能尽早举办,多多参与。
相关源代码
-
加入了学习《pico w贪吃蛇的演示-1》,观看 贪吃蛇演示-1
- 2023-05-31
-
加入了学习《直播回放: TI 超声波镜头清洁技术》,观看 TI 超声波镜头清洁技术