K230-CanMV 开发板 — 代码例程
例程 1:CanMV — 摄像头采集 + AI 物体检测
import time
import os
from media.camera import *
from media.display import *
from media.media import *
from libs.Utils import *
# 初始化摄像头(MIPI CSI0,IMX335 传感器)
camera = Camera()
camera.set_outdev(2, 0) # 输出到 VF (Video Frame)
# 传感器配置
sensor = camera.sensor()
sensor.reset()
sensor.set_framesize(SENSOR_1920X1080)
sensor.set_pixformat(SENSOR_RGB888)
# 初始化 HDMI 显示
display = Display(Display.VIRT, 1920, 1080)
display.set_ideal_size(1920, 1080)
display.set_backlight(100)
# 初始化 AI
from libs.AIBase import AIBase
from libs.YOLO import YOLO
yolo = YOLO("/sdcard/models/yolov5s.kmodel", 0.5, 0.4)
# 主循环
MediaManager.init()
camera.start()
display.show()
try:
while True:
img = camera.capture_image()
if img is None:
continue
# AI 推理
results = yolo.run(img)
# 画检测框
for det in results:
x, y, w, h = det['bbox']
cls = det['class']
conf = det['confidence']
img.draw_rectangle(x, y, w, h, color=(0, 255, 0), thickness=2)
img.draw_string(x, y - 20,
f"{cls} {conf:.2f}",
color=(0, 255, 0), scale=2)
display.show(img)
del img
except KeyboardInterrupt:
pass
finally:
camera.stop()
display.deinit()
MediaManager.deinit()
例程 2:CanMV — 双路摄像头同时采集
from media.camera import *
from media.display import *
from media.media import *
# 摄像头 0 (MIPI CSI0 - IMX335)
cam0 = Camera(id=0)
cam0.sensor().set_framesize(SENSOR_1280X720)
cam0.sensor().set_pixformat(SENSOR_RGB888)
# 摄像头 1 (MIPI CSI1 - OV5647)
cam1 = Camera(id=1)
cam1.sensor().set_framesize(SENSOR_1280X720)
cam1.sensor().set_pixformat(SENSOR_RGB888)
# HDMI 显示(画中画)
display = Display(Display.VIRT, 1920, 1080)
MediaManager.init()
cam0.start()
cam1.start()
display.show()
try:
while True:
img0 = cam0.capture_image()
img1 = cam1.capture_image()
if img0 and img1:
# 拼接左右双画面
img0.draw_image(img1, 960, 0) # 右半部分
img0.draw_string(10, 10, "CAM0 (Left)", color=(0,255,0), scale=2)
img0.draw_string(970, 10, "CAM1 (Right)", color=(0,255,0), scale=2)
display.show(img0)
del img0, img1
except KeyboardInterrupt:
cam0.stop()
cam1.stop()
display.deinit()
MediaManager.deinit()
例程 3:CanMV — 40Pin GPIO 控制 (树莓派兼容)
from machine import Pin, PWM, I2C, UART
import time
# --- GPIO 输出 ---
led = Pin(12, Pin.OUT) # GPIO12 (Pin 32)
for _ in range(5):
led.value(1)
time.sleep(0.3)
led.value(0)
time.sleep(0.3)
# --- PWM ---
pwm = PWM(Pin(13), freq=1000, duty=50) # GPIO13 (Pin 33)
print(f"PWM: freq={pwm.freq()}, duty={pwm.duty()}")
for d in range(0, 101, 5):
pwm.duty(d)
time.sleep(0.05)
pwm.deinit()
# --- I2C 扫描 ---
i2c = I2C(1, freq=100000) # I2C1: GPIO2(SDA), GPIO3(SCL)
devices = i2c.scan()
print(f"I2C devices found: {[hex(d) for d in devices]}")
# --- UART 发送 ---
uart = UART(2, baudrate=115200) # GPIO14(TX), GPIO15(RX)
uart.write("Hello from K230 CanMV!\r\n")
print(f"UART RX: {uart.read()}")
例程 4:CanMV — Wi-Fi 6 连接 + MQTT 物联网
import network
import time
from umqtt.simple import MQTTClient
# Wi-Fi 6 连接
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("YOUR_SSID", "YOUR_PASSWORD")
print("Connecting to Wi-Fi 6...")
while not wlan.isconnected():
time.sleep(0.5)
print(f"Connected! IP: {wlan.ifconfig()[0]}")
print(f"RSSI: {wlan.status('rssi')} dBm")
# MQTT 连接
mqtt = MQTTClient(
client_id="K230-CanMV",
server="broker.emqx.io",
port=1883
)
mqtt.connect()
print("MQTT connected!")
# 订阅主题
def on_message(topic, msg):
print(f"[MQTT] {topic.decode()}: {msg.decode()}")
mqtt.set_callback(on_message)
mqtt.subscribe(b"k230/command")
# 定时发布传感器数据
counter = 0
try:
while True:
mqtt.check_msg()
mqtt.publish(b"k230/status", f"Uptime: {counter}s".encode())
counter += 5
time.sleep(5)
except KeyboardInterrupt:
mqtt.disconnect()
wlan.disconnect()
例程 5:CanMV — 人脸识别门禁(完整流程)
import time
from media.camera import *
from media.display import *
from media.media import *
from machine import Pin
from libs.FaceRecognition import FaceRecognition
# 初始化
camera = Camera()
camera.sensor().set_framesize(SENSOR_640X480)
display = Display(Display.VIRT, 640, 480)
# 人脸识别引擎
face_rec = FaceRecognition("/sdcard/models/face_detect.kmodel",
"/sdcard/models/face_recognize.kmodel")
# 注册人脸(管理员)
print("Registering admin face...")
admin_img = camera.capture_image()
face_rec.register("admin", admin_img)
print("Admin face registered!")
# 门锁继电器 (GPIO12, 低电平触发)
lock = Pin(12, Pin.OUT)
lock.value(1) # 默认锁定
MediaManager.init()
camera.start()
display.show()
try:
while True:
img = camera.capture_image()
if img is None:
continue
# 人脸识别
results = face_rec.recognize(img)
for r in results:
name = r['name']
conf = r['confidence']
x, y, w, h = r['bbox']
color = (0, 255, 0) if name == "admin" and conf > 0.75 else (255, 0, 0)
img.draw_rectangle(x, y, w, h, color=color, thickness=2)
img.draw_string(x, y - 16, f"{name} {conf:.2f}",
color=color, scale=1)
# 管理员识别成功 → 开门
if name == "admin" and conf > 0.75:
lock.value(0) # 开门
img.draw_string(200, 10, "DOOR OPENED!",
color=(0, 255, 0), scale=3)
time.sleep(3)
lock.value(1) # 关门
display.show(img)
del img
except KeyboardInterrupt:
pass
finally:
camera.stop()
display.deinit()
MediaManager.deinit()
lock.value(1)
例程 6:CanMV — 以太网 + HTTP 服务器
import network
import socket
# 初始化以太网
eth = network.LAN()
eth.active(True)
while not eth.isconnected():
pass
print(f"Ethernet connected! IP: {eth.ifconfig()[0]}")
# 简易 HTTP 服务器
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(addr)
s.listen(5)
print(f"HTTP server on http://{eth.ifconfig()[0]}")
HTML = """HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n
<html><body>
<h1>K230-CanMV Server</h1>
<p>AI Edge Computing Platform</p>
<p>6 TOPS NPU | RISC-V 1.6GHz | Wi-Fi 6</p>
</body></html>"""
while True:
cl, addr = s.accept()
print(f"Request from {addr}")
cl.send(HTML.encode())
cl.close()
开发环境配置
| 步骤 |
操作 |
| 1. 安装 CanMV IDE |
下载 CanMV IDE |
| 2. 连接开发板 |
USB Type-C (OTG口) 连接电脑 |
| 3. 选择设备 |
CanMV IDE → 工具 → 选择串口 → K230 |
| 4. 上传代码 |
直接在 IDE 中运行或保存到 /sdcard/main.py 自动启动 |
| 5. 模型转换 |
使用 nncase 工具将 ONNX/TFLite → kmodel,放入 SD 卡 |