MicroPython 智能硬件开发完整指南

第一部分:MicroPython 基础

1. MicroPython简介

  • 定义:专为微控制器设计的精简Python 3实现,支持硬件直接操作。
  • 特点
    • 语法兼容Python 3,但移除复杂功能(如多线程)。
    • 支持GPIO、PWM、I2C、SPI等硬件接口。
    • 适用于ESP32、ESP8266、Raspberry Pi Pico等开发板。

2. 开发环境搭建

硬件准备
  • 推荐开发板:ESP32(性价比高,WiFi/BLE双模)、Raspberry Pi Pico(低成本,RP2040芯片)。
  • 外设:杜邦线、面包板、传感器(DHT11、超声波模块等)。
软件配置
  1. 固件烧录
    • 下载固件:MicroPython官网
    • 烧录工具:esptool(ESP系列)、rp2-flash(树莓派Pico)。
  2. 编程工具
    • Thonny IDE(新手友好,内置REPL)。
    • VS Code + Pymakr插件(支持远程调试)。
第一个程序
# 点亮板载LED(ESP32示例)
from machine import Pin
import time

led = Pin(2, Pin.OUT)
while True:
    led.toggle()
    time.sleep(1)

第二部分:核心语法与硬件操作

1. 基础语法

变量与数据类型
# MicroPython支持标准Python类型
value = 42
name = "ESP32"
data = [1, 2, 3]
sensor_data = {
   "temp": 25.5, "humi": 60}
流程控制
# 条件与循环
if temperature > 30:
    alert()
elif temperature < 0:
    freeze()
else:
    normal()

for i in range(10):
    print(i)

while sensor.is_active():
    read_data()

2. 硬件交互

GPIO控制
from machine import Pin

button = Pin(14, Pin.IN, Pin.PULL_UP)  # 按钮输入(上拉模式)
led = Pin(2, Pin.OUT)                 # LED输出

if button.value() == 0:  # 按钮按下
    led.on()
PWM调光/调速
from machine import PWM, Pin

pwm = PWM(Pin(13), freq=1000, duty=512)  # 频

你可能感兴趣的:(Python,智能硬件)