🖥️ 一、输出设备:屏幕显示 (ST7789)

✨ 显示英文 Hello World
import st7789py as st7789
import tft_config
import vga2_bold_16x32 as font

tft = tft_config.config()
tft.fill(st7789.BLACK)
tft.text(font, "Hello World!", 50, 150, st7789.WHITE)
🔍 关键语句解析
tft.fill(st7789.BLACK) → 清屏为黑色,相当于擦掉画板。
tft.text(font, "文字", x, y, 颜色) → 在坐标(x,y)显示文字,字体要提前导入。
st7789.WHITE → 白色,也可以用 RED, GREEN, YELLOW 等改变文字颜色。
📊 显示多个ADC值(电位器/光敏)
from machine import Pin, ADC
import st7789py as st7789
import tft_config
import vga2_bold_16x32 as font

pins = [(8, 70), (9, 120), (13, 170)]
adcs = [(ADC(Pin(p)), y) for p, y in pins]
for adc, _ in adcs: adc.atten(ADC.ATTN_11DB)

tft = tft_config.config(rotation=0)
tft.fill(st7789.BLACK)
for i, (p, y) in enumerate(pins):
    tft.text(font, f"A{p}:", 20, y, st7789.WHITE)

while True:
    for adc, y in adcs:
        tft.fill_rect(80, y, 80, 32, st7789.BLACK)
        tft.text(font, str(adc.read()), 80, y, st7789.GREEN)
    time.sleep(0.2)
🔍 关键语句解析
ADC(Pin(p)).atten(ADC.ATTN_11DB) → 设置ADC量程0-3.3V。
tft.fill_rect(x, y, w, h, color) → 清除小区域,防止数字重叠。
adc.read() → 读取0~4095的数值,模拟量转数字。
🔘 实时显示按键电平 (GPIO4,5,16,17,38,39)
import st7789py as st7789
import tft_config
import vga2_bold_16x32 as font
from machine import Pin
import time

pins = [("4",4,100,60), ("5",5,100,95), ("17",17,180,95),
        ("16",16,100,130), ("38",38,100,235), ("39",39,180,235)]
for name, pin, x, y in pins:
    Pin(pin, Pin.IN, Pin.PULL_UP)

tft = tft_config.config(rotation=0)
tft.fill(st7789.BLACK)
for name, pin, x, y in pins:
    tft.text(font, f"GPIO{name}:", x-80, y, st7789.WHITE)

while True:
    for name, pin, x, y in pins:
        val = Pin(pin).value()
        tft.fill_rect(x, y, 30, 32, st7789.BLACK)
        tft.text(font, str(val), x, y, st7789.GREEN if val else st7789.RED)
    time.sleep(0.1)
🔍 关键语句解析
Pin(pin, Pin.IN, Pin.PULL_UP) → 按键输入并开启内部上拉,未按下时读数为1,按下为0。
tft.fill_rect(x, y, w, h, st7789.BLACK) → 刷新数值区域避免残留。
• 三目运算 st7789.GREEN if val else st7789.RED → 按下红色,释放绿色。
📏 超声波测距+绿色条状图
import st7789py as st7789
import tft_config
import vga2_bold_16x32 as font
from machine import Pin, time_pulse_us
import time

trig = Pin(2, Pin.OUT)
echo = Pin(3, Pin.IN)
tft = tft_config.config(rotation=0)
tft.fill(st7789.BLACK)

def get_cm():
    trig.value(0); time.sleep_us(2)
    trig.value(1); time.sleep_us(10); trig.value(0)
    return time_pulse_us(echo, 1, 30000) * 0.034 / 2

while True:
    d = get_cm()
    h = int(320 * min(d, 20) / 20)
    tft.fill_rect(130, 10, 70, 32, st7789.BLACK)
    tft.text(font, f"{d:.1f}", 130, 10, st7789.YELLOW)
    tft.fill_rect(10, 0, 30, 320, st7789.BLACK)
    tft.rect(10, 0, 30, 320, st7789.WHITE)
    if h > 0: tft.fill_rect(10, 320 - h, 30, h, st7789.GREEN)
    time.sleep(0.1)
🔍 关键语句解析
time_pulse_us(echo, 1, 30000) → 测量Echo引脚高电平时长(微秒),最长等待30ms。
• 距离计算公式: 距离cm = 高电平时间 × 0.034 / 2
tft.fill_rect(10, 320 - h, 30, h, st7789.GREEN) → 动态绘制绿色柱状条,高度随距离变化。

💡 二、输出设备:LED、蜂鸣器、电机、舵机

🚦 红绿LED交替闪烁
from machine import Pin
import time
ledr = Pin(14, Pin.OUT)
ledg = Pin(15, Pin.OUT)
while True:
    ledr.value(1); ledg.value(0)
    time.sleep(1)
    ledr.value(0); ledg.value(1)
    time.sleep(1)
🔍 关键语句解析
Pin(14, Pin.OUT) → 设置GPIO14为数字输出模式。
value(1) → 高电平点亮LED,value(0)熄灭。
time.sleep(1) → 等待1秒。
🌊 呼吸灯效果 (PWM调光)
from machine import Pin, PWM
from time import sleep
led = PWM(Pin(14), freq=1000)
while True:
    for duty in range(0, 1024, 5):
        led.duty(duty)
        sleep(0.005)
    for duty in range(1023, -1, -5):
        led.duty(duty)
        sleep(0.005)
🔍 关键语句解析
PWM(Pin(14), freq=1000) → 创建PWM对象,频率1000Hz。
duty(duty) → 占空比0~1023,值越大越亮。
• 循环渐变实现柔和呼吸灯。
🎵 蜂鸣器发声 (主动蜂鸣器)
from machine import Pin, PWM
import time
def tone_once(pin=46, freq=1000, ms=300):
    pwm = PWM(Pin(pin))
    pwm.freq(freq); pwm.duty(512)
    time.sleep(ms/1000)
    pwm.duty(0); pwm.deinit()

tone_once(pin=46, freq=1000, ms=500)
tone_once(pin=46, freq=1500, ms=500)
🔍 关键语句解析
PWM(Pin(pin)).freq(freq) → 设置声音频率,不同频率产生不同音调。
duty(512) → 50%占空比让蜂鸣器响度适中。
deinit() → 释放PWM通道。
⚙️ 直流电机控制 (PWM调速)
from machine import Pin, PWM
speed = PWM(Pin(7), freq=5000)   # 使能/调速
d = Pin(19, Pin.OUT)             # 方向
d.value(1)       # 正转
speed.duty(0)    # 全速(注意逻辑根据驱动板)
# speed.duty(1023) 全速另一方向
d.value(0)
speed.duty(500)  # 半速
🔍 关键语句解析
• PWM引脚控制电机速度;普通IO控制正反转。
duty(0)duty(1023) 对应最大转速;
• 注意:不同驱动板逻辑可能相反,可先测试。
🕹️ 舵机转动 (SG90)
import time
from servo import Servo
my_servo = Servo(pin_id=28)
my_servo.write(30)   # 转到30度
time.sleep(2)
my_servo.write(90)   # 转到90度
🔍 关键语句解析
• 需要提前将 servo.py 库上传到开发板。
Servo(pin_id=28) 指定信号引脚。
write(角度) → 0~180度控制舵机位置。

🌈 三、智能RGB灯带 (WS2812 / NeoPixel)

🟢 点亮12个绿灯
import machine, neopixel
np = neopixel.NeoPixel(machine.Pin(48), 12)
for i in range(12):
    np[i] = (0, 250, 0)   # R,G,B
np.write()
🔍 关键语句解析
NeoPixel(pin, 数量) → 控制可编程RGB灯带。
np[i] = (R,G,B) 设置第i个灯颜色。
np.write() → 将数据发送到灯带,必须调用才会显示。
🎲 随机颜色呼吸效果
import machine, neopixel, random, time
np = neopixel.NeoPixel(machine.Pin(48), 12)
brightness = 0.3
while True:
    for i in range(12):
        r = int(random.randint(0,255)*brightness)
        g = int(random.randint(0,255)*brightness)
        b = int(random.randint(0,255)*brightness)
        np[i] = (r, g, b)
    np.write()
    time.sleep(1)
🔍 关键语句解析
random.randint(0,255) → 随机0~255数值,让颜色千变万化。
• 乘以亮度系数 brightness 避免灯光刺眼。
• 刷新所有灯后延时1秒,实现节奏变化。
⏰ 时钟灯带 (秒针逐一点亮)
import machine, neopixel, time
np = neopixel.NeoPixel(machine.Pin(48), 12)
GREEN = (0, int(255*0.3), 0)
OFF = (0,0,0)
while True:
    for i in range(12):
        np[i] = OFF
    np.write()
    for i in range(12):
        np[i] = GREEN
        np.write()
        time.sleep(1)
🔍 关键语句解析
• 先全部熄灭,再依次点亮一颗灯,模拟秒针走动。
• 每亮一颗灯等待1秒,12秒后循环。
• 可改变颜色列表做出彩虹秒针。

🎚️ 四、传感器输入:按键、电位器、超声波、AHT20温湿度

🔌 读取按键状态 (GPIO38)
from machine import Pin
from time import sleep
button = Pin(38, Pin.IN)
while True:
    print(button.value())
    sleep(0.1)
🔍 关键语句解析
Pin(38, Pin.IN) → 设置为输入模式。
button.value() 返回0(按下) 或 1(未按)。
• 简单循环打印可检测按键状态。
🎚️ 读取电位器 (ADC8)
from machine import Pin, ADC
from time import sleep
pot = ADC(Pin(8))
pot.atten(ADC.ATTN_11DB)   # 满量程3.3V
while True:
    print(pot.read())
    sleep(0.1)
🔍 关键语句解析
ADC(Pin(8)) 使用ADC通道,电位器转动改变电压。
atten(ADC.ATTN_11DB) 允许测量0~3.3V。
read() 返回0-4095,数值随旋钮位置改变。
📡 超声波测距 (HC-SR04)
from hcsr04 import HCSR04
from time import sleep
sensor = HCSR04(trigger_pin=2, echo_pin=3)
while True:
    distance = sensor.distance_cm()
    print('Distance:', distance, 'cm')
    sleep(0.2)
🔍 关键语句解析
• 需要提前将 hcsr04.py 驱动上传到板子。
• 封装好的库直接返回厘米数,原理为声速测距。
• 常用于避障或倒车雷达。
🌡️ AHT20 温湿度传感器 (I2C)
from machine import Pin, SoftI2C
import ahtx0
import time
i2c = SoftI2C(scl=Pin(0), sda=Pin(1))
sensor = ahtx0.AHT20(i2c)
while True:
    print(f"温度:{sensor.temperature:.1f}°C 湿度:{sensor.relative_humidity:.1f}%")
    time.sleep(1)
🔍 关键语句解析
SoftI2C(scl, sda) 模拟I2C总线连接传感器。
• 使用库 ahtx0.py 简化读取。
sensor.temperature 返回摄氏温度,relative_humidity 返回相对湿度。
☀️ 环境光检测 (光敏电阻)
from machine import Pin, ADC
import time
light = ADC(Pin(9))
light.atten(ADC.ATTN_11DB)
while True:
    val = light.read()
    print(f"光线值:{val} (值越小越亮)")
    time.sleep(0.5)
🔍 关键语句解析
• 光敏电阻与固定电阻分压,ADC测量电压变化。
• 强光时电阻变小,ADC数值降低;黑暗数值升高。
• 可以配合自动夜灯项目。

🎨 五、综合绘图&艺术图形 (画圆/矩形/三角形)

✏️ 图形绘制演示
# 参考 DrawAll.py 片段
import st7789py as st7789
import tft_config
import math
tft = tft_config.config()
tft.fill(st7789.BLACK)
# 画空心圆
def draw_circle(x0,y0,r,color):
    #  Bresenham算法
    ...
draw_circle(60,60,40,st7789.RED)
tft.rect(20,20,80,60,st7789.GREEN)
tft.fill_rect(80,50,50,50,st7789.BLUE)
🔍 关键语句解析
tft.rect(x,y,w,h,color) 绘制矩形边框。
tft.fill_rect 填充矩形。
• 复杂的圆形/椭圆通过像素点逐个计算,培养数学逻辑。
• 用 display.pixel() 可绘制任何形状。
🎨 随机飘动文字
import random, time
import st7789py as st7789
import tft_config
import vga2_bold_16x32 as font
tft = tft_config.config()
while True:
    tft.fill(st7789.BLACK)
    x = random.randint(0, tft.width - 80)
    y = random.randint(0, tft.height - 40)
    col = st7789.color565(random.getrandbits(8),
                          random.getrandbits(8),
                          random.getrandbits(8))
    tft.text(font, "Hello!", x, y, col)
    time.sleep(1)
🔍 关键语句解析
random.randint(0,width) 让文字随机跑动。
color565(r,g,b) 混合出自定义颜色。
• 每次清屏后重新绘制,像动画一样。