MicroPython 代码例程

知识库
知识库文档
/firmware/开发板/ESP32-C3-DevKitM-1 开发板/ESP32-C3-DevKitM-1 开发板 — Arduino/MicroPython 代码例程.md

文档

ESP32-C3-DevKitM-1 开发板 — 代码例程

例程 1:Arduino — 板载 RGB LED 呼吸灯

#include <Adafruit_NeoPixel.h>

#define RGB_PIN   8      // WS2812 RGB LED 接到 GPIO8
#define NUMPIXELS 1

Adafruit_NeoPixel pixels(NUMPIXELS, RGB_PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  pixels.begin();
  pixels.setBrightness(32);
}

void loop() {
  // 呼吸效果:0 → 255 → 0
  for (int i = 0; i <= 255; i++) {
    pixels.setPixelColor(0, pixels.Color(i, 0, 255 - i));
    pixels.show();
    delay(5);
  }
  for (int i = 255; i >= 0; i--) {
    pixels.setPixelColor(0, pixels.Color(i, 0, 255 - i));
    pixels.show();
    delay(5);
  }
}

例程 2:Arduino — Wi-Fi + I2C OLED 网络时钟

#include <WiFi.h>
#include <U8g2lib.h>
#include <NTPClient.h>
#include <WiFiUdp.h>

#define SDA_PIN  4
#define SCL_PIN  5

U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "ntp.aliyun.com", 28800); // UTC+8

const char* ssid     = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";

void setup() {
  Serial.begin(115200);
  Wire.begin(SDA_PIN, SCL_PIN);
  u8g2.begin();

  WiFi.begin(ssid, password);
  u8g2.clearBuffer();
  u8g2.setFont(u8g2_font_6x10_tf);
  u8g2.drawStr(0, 10, "WiFi connecting...");
  u8g2.sendBuffer();

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }

  timeClient.begin();
  u8g2.clearBuffer();
  u8g2.drawStr(0, 10, "WiFi OK!");
  u8g2.sendBuffer();
  delay(1000);
}

void loop() {
  timeClient.update();

  u8g2.clearBuffer();
  u8g2.setFont(u8g2_font_10x20_tf);

  String timeStr = timeClient.getFormattedTime();
  char buf[10];
  timeStr.substring(0, 8).toCharArray(buf, 9);

  u8g2.drawStr(20, 40, buf);
  u8g2.drawStr(0, 60, "ESP32-C3 IoT Clock");
  u8g2.sendBuffer();

  delay(1000);
}

例程 3:Arduino — 低功耗深度睡眠 + GPIO 唤醒

#include <driver/rtc_io.h>

#define WAKEUP_PIN  GPIO_NUM_1  // 按钮唤醒引脚
#define LED_PIN     8           // RGB LED

RTC_DATA_ATTR int bootCount = 0;

void setup() {
  Serial.begin(115200);
  delay(100);

  Serial.printf("Boot count: %d\n", ++bootCount);

  // 配置唤醒源:GPIO1 上升沿唤醒
  esp_sleep_enable_ext0_wakeup(WAKEUP_PIN, 1);

  // LED 闪烁一下表示醒来
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, HIGH);
  delay(200);
  digitalWrite(LED_PIN, LOW);

  Serial.println("Going to deep sleep... Wake me with GPIO1 HIGH.");
  delay(500);
  esp_deep_sleep_start();  // 深度睡眠
}

void loop() {
  // 永远不会执行到这里
}

例程 4:MicroPython — Wi-Fi 扫描 + RGB LED 信号指示

import network
import time
from machine import Pin
from neopixel import NeoPixel

# 初始化 RGB LED
np = NeoPixel(Pin(8), 1)
np[0] = (0, 0, 0)
np.write()

# Wi-Fi 扫描
wlan = network.WLAN(network.STA_IF)
wlan.active(True)

print("Scanning Wi-Fi networks...")
networks = wlan.scan()

for i, net in enumerate(networks[:10]):
    ssid = net[0].decode('utf-8')
    rssi = net[3]
    print(f"{i+1}. {ssid} (RSSI: {rssi} dBm)")

    # 信号强 → 绿色,中等 → 蓝色,弱 → 红色
    if rssi > -60:
        np[0] = (0, 32, 0)   # 绿色
    elif rssi > -75:
        np[0] = (0, 0, 32)   # 蓝色
    else:
        np[0] = (32, 0, 0)   # 红色
    np.write()
    time.sleep(0.5)

np[0] = (0, 0, 0)
np.write()
print("Scan complete.")

例程 5:MicroPython — PWM 控制 LED 亮度 + ADC 电位器输入

from machine import Pin, PWM, ADC
import time

# PWM 输出 (GPIO3)
led_pwm = PWM(Pin(3), freq=1000)

# ADC 读取电位器 (GPIO0 = ADC1_CH0)
pot = ADC(Pin(0))
pot.atten(ADC.ATTN_11DB)  # 量程 0~3.3V

while True:
    val = pot.read()              # 0~4095
    duty = int(val * 1023 / 4095) # 映射到 PWM 0~1023
    led_pwm.duty(duty)

    print(f"ADC: {val:4d}  PWM Duty: {duty:4d}")
    time.sleep(0.1)

例程 6:MicroPython — BLE 温度外设广播

import bluetooth
import struct
import time
from machine import ADC, Pin

# BLE 初始化
ble = bluetooth.BLE()
ble.active(True)

# 内部温度传感器(ESP32-C3 内置)
temp_sensor = ADC(Pin(4))  # 使用内部通道
temp_sensor.atten(ADC.ATTN_11DB)

# 环境服务 UUID (0x181A)
_ENV_SENSE_UUID = bluetooth.UUID(0x181A)
_TEMP_CHAR_UUID  = bluetooth.UUID(0x2A6E)

# 注册服务
temp_char = (_TEMP_CHAR_UUID, bluetooth.FLAG_READ | bluetooth.FLAG_NOTIFY)
env_service = (_ENV_SENSE_UUID, (temp_char,))
services = (env_service,)
((temp_handle,),) = ble.gatts_register_services(services)

def read_temperature():
    raw = temp_sensor.read()
    voltage = raw * 3.3 / 4095
    temp_c = (voltage - 0.5) * 100  # 粗略换算
    return int(temp_c * 100)         # 返回 centi-Celsius

# 开始广播
advertising_payload = struct.pack('BB', 0x02, 0x01) + \
                      struct.pack('BB', 0x03, 0x02)
ble.gap_advertise(100_000, adv_data=advertising_payload)

print("BLE Temperature Beacon started...")
while True:
    temp_val = read_temperature()
    ble.gatts_write(temp_handle, struct.pack('<h', temp_val))
    ble.gatts_notify(0, temp_handle, struct.pack('<h', temp_val))
    print(f"Temperature: {temp_val / 100:.2f} °C")
    time.sleep(2)

开发环境快速配置

环境 关键配置
Arduino IDE 开发板管理器 URL: https://espressif.github.io/arduino-esp32/package_esp32_index.json → 选择 ESP32C3 Dev Module
PlatformIO board = esp32-c3-devkitm-1,框架选 arduinoespidf
MicroPython 先烧录 ESP32_GENERIC_C3-2024xxxx.bin,使用 esptool.py --chip esp32c3 --port COMx write_flash 0x0 firmware.bin
ESP-IDF idf.py set-target esp32c3 && idf.py build flash monitor

信息

路径
/firmware/开发板/ESP32-C3-DevKitM-1 开发板/ESP32-C3-DevKitM-1 开发板 — Arduino/MicroPython 代码例程.md
更新时间
2026/5/26