Sipeed Maix Bit K210 开发板 — MaixPy/C 代码例程.md
# Sipeed Maix Bit K210 开发板 — 代码例程
## 例程 1:MaixPy (MicroPython) — 人脸检测
```python
import sensor
import image
import lcd
import KPU as kpu
# 初始化 LCD
lcd.init(freq=15000000)
lcd.rotation(2)
# 初始化摄像头
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA) # 320x240
sensor.set_hmirror(1)
sensor.set_vflip(1)
sensor.run(1)
# 加载人脸检测模型(需先将 kmodel 放入 SD 卡)
task = kpu.load("/sd/face_detect.kmodel")
anchor = (1.889, 2.525, 2.947, 3.941, 3.982, 5.366, 5.154, 6.861)
# 设置 KPU 参数
kpu.init_yolo2(task, 0.5, 0.3, 5, anchor)
print("Face detection started!")
while True:
img = sensor.snapshot()
objects = kpu.run_yolo2(task, img)
if objects:
for obj in objects:
# 画框
img.draw_rectangle(obj.rect(), color=(0, 255, 0), thickness=2)
img.draw_string(obj.x(), obj.y() - 16,
"Face %.2f" % obj.value(),
color=(0, 255, 0), scale=1)
lcd.display(img)
```
---
## 例程 2:MaixPy — I2C OLED + GPIO 中断
```python
from fpioa_manager import fm
from machine import I2C, Pin
import time
# FPIOA 映射 I2C
fm.register(34, fm.fpioa.I2C0_SCLK)
fm.register(35, fm.fpioa.I2C0_SDA)
i2c = I2C(I2C.I2C0, freq=100000)
# 扫描 I2C 设备
devices = i2c.scan()
print(f"I2C devices: {[hex(d) for d in devices]}")
# 初始化 SSD1306 OLED
# (需导入 ssd1306 库)
# from ssd1306 import SSD1306_I2C
# oled = SSD1306_I2C(128, 64, i2c)
# oled.text("Maix Bit K210", 0, 0)
# oled.show()
# GPIO 中断演示
fm.register(36, fm.fpioa.GPIOHS0)
button = Pin(Pin.GPIOHS0, Pin.IN, Pin.PULL_UP)
count = 0
def on_press(pin):
global count
count += 1
print(f"Button pressed! Count: {count}")
button.irq(on_press, Pin.IRQ_FALLING)
print("Waiting for button press on IO36...")
while True:
time.sleep(1)
```
---
## 例程 3:MaixPy — RGB LED + PWM 控制
```python
from fpioa_manager import fm
from machine import Timer, PWM
import time
# RGB LED 是 WS2812,用 PWM+DMA 或专用模块
# 这里演示普通 PWM 输出控制 LED 亮度
fm.register(36, fm.fpioa.TIMER0_TOGGLE1)
# PWM 输出
pwm = PWM(Timer.TIMER0, freq=1000, duty=50, pin=36)
print("PWM on IO36, 1kHz, 50% duty")
# 呼吸效果
for duty in range(0, 101, 5):
pwm.duty(duty)
time.sleep(0.02)
for duty in range(100, -1, -5):
pwm.duty(duty)
time.sleep(0.02)
pwm.disable()
print("PWM demo done.")
```
---
## 例程 4:C SDK — KPU 数字识别
```c
#include <stdio.h>
#include <stdlib.h>
#include "kpu.h"
#include "dvp.h"
#include "lcd.h"
#include "fpioa.h"
// KPU 模型数据结构(模型编译后自动生成)
extern unsigned char gImage_image[];
extern unsigned long gImage_image_len;
static kpu_model_context_t task;
int main() {
// 初始化 FPIOA
fpioa_set_function(24, FUNC_GPIOHS0 + 24);
// 初始化 LCD
lcd_init();
lcd_set_direction(DIR_YX_RLDU);
// 初始化 DVP 摄像头
dvp_init(8);
dvp_set_framesize(FRAMESIZE_QVGA);
dvp_set_pixformat(PIXFORMAT_RGB565);
// 加载 KPU 模型
if (kpu_load_kmodel(&task, gImage_image) != 0) {
printf("KPU model load failed!\n");
return -1;
}
printf("KPU model loaded. Starting inference...\n");
uint8_t *img_data;
while (1) {
// 获取摄像头帧
img_data = dvp_get_frame();
if (img_data == NULL) continue;
// 运行 KPU 推理
kpu_run_kmodel(&task, img_data, DMAC_CHANNEL5,
kpu_done_callback, NULL);
// 获取输出
float *output;
size_t output_size;
kpu_get_output(&task, 0, &output, &output_size);
// 找最大概率的类别
int max_idx = 0;
float max_val = output[0];
for (size_t i = 1; i < output_size / sizeof(float); i++) {
if (output[i] > max_val) {
max_val = output[i];
max_idx = i;
}
}
printf("Predicted class: %d (confidence: %.2f%%)\n",
max_idx, max_val * 100);
// 显示到 LCD
lcd_draw_string(10, 10, "Class: %d", max_idx);
lcd_draw_string(10, 30, "Conf: %.1f%%", max_val * 100);
}
return 0;
}
```
---
## 例程 5:MaixPy — MicroSD 文件系统 + 模型加载
```python
import os
import uos
from machine import SDCard
# 挂载 SD 卡
try:
sd = SDCard()
uos.mount(sd, '/sd')
print("SD card mounted!")
except Exception as e:
print(f"SD mount failed: {e}")
# 列出 SD 卡内容
if '/sd' in uos.listdir('/'):
print("\nSD Card contents:")
for item in os.listdir('/sd'):
stat = os.stat('/sd/' + item)
size = stat[6]
print(f" {item:30s} {size:>8d} bytes")
# 加载 AI 模型
import KPU as kpu
model_files = [f for f in os.listdir('/sd') if f.endswith('.kmodel')]
if model_files:
model_path = '/sd/' + model_files[0]
print(f"\nLoading model: {model_path}")
try:
task = kpu.load(model_path)
print("Model loaded successfully!")
except Exception as e:
print(f"Model load failed: {e}")
else:
print("\nNo .kmodel files found on SD card!")
```
---
## 开发环境快速配置
| 环境 | 关键步骤 |
|------|---------|
| **MaixPy IDE** | 1. 安装驱动 (CH340) 2. 用 `kflash_gui` 烧入 MaixPy 固件 3. 打开 MaixPy IDE 连接 COM 口 |
| **PlatformIO** | `pio init -b sipeed-maix-bit` |
| **C SDK** | 安装 Kendryte toolchain → `cmake .. -DPROJ=hello_world -DTOOLCHAIN=/opt/kendryte-toolchain` |