AI+嵌入式方向学习路线

0 阅读16分钟

📚 第一阶段:基础知识(3-4个月)

1. 嵌入式基础

C语言进阶(1个月)

// 必须掌握的核心知识
1. 指针和内存管理
   - 指针数组、数组指针、函数指针
   - 动态内存分配(malloc/free)
   - 内存对齐、内存泄漏检测

2. 数据结构(嵌入式常用)
   - 链表、队列、栈(纯C实现)
   - 循环缓冲区
   - 状态机

3. 位操作
   - 移位、掩码、位域
   - 寄存器操作

4. 嵌入式编程规范
   - volatile 关键字
   - 中断安全的代码
   - 代码优化技巧

// 示例:GPIO 寄存器操作
#define GPIO_BASE 0x40020000
#define SET_BIT(reg, bit)   ((reg) |= (1 << (bit)))
#define CLEAR_BIT(reg, bit) ((reg) &= ~(1 << (bit)))

推荐资源

  • 书籍:《C和指针》、《C专家编程》
  • 在线:牛客网C语言专项
  • 项目:用C实现常用数据结构

单片机基础(1.5个月)

学习路线:
Arduino(入门)→ STM32(主流)→ ESP32(WiFi+BT)

Arduino 阶段(2周):
├─ 开发板:Arduino Uno
├─ 基础实验
│  ├─ GPIO:LED、按键、中断
│  ├─ 定时器:PWM、延时
│  ├─ 串口通信:UART
│  ├─ I2C/SPI:传感器通信
│  └─ ADC:模拟信号采集
└─ 小项目:温湿度采集系统

STM32 阶段(4周):
├─ 开发板:STM32F103/STM32F407
├─ 开发环境:STM32CubeMX + Keil/STM32CubeIDE
├─ 核心知识
│  ├─ HAL库/寄存器操作
│  ├─ 时钟配置
│  ├─ 中断优先级
│  ├─ DMA 数据搬运
│  ├─ RTOS(FreeRTOS)
│  └─ 低功耗模式
└─ 项目:多传感器数据采集+串口上报

ESP32 阶段(2周):
├─ 开发板:ESP32-DevKitC
├─ 特色功能
│  ├─ WiFi/蓝牙通信
│  ├─ ESP-IDF 框架
│  └─ OTA 远程升级
└─ 项目:物联网数据采集节点

推荐资源

  • 视频:B站"正点原子STM32教程"
  • 书籍:《STM32库开发实战指南》
  • 开发板:淘宝购买套装(200-300元)

Linux嵌入式(1个月)

# 学习路线
基础命令 → Shell脚本 → 交叉编译 → 驱动开发入门

1. Linux基础(1周)
   - 文件操作、权限管理
   - vi/vim 编辑器
   - gcc/make/gdb 工具链
   
2. Shell脚本(1周)
   - 变量、循环、条件判断
   - 文本处理(grep/sed/awk)
   - 自动化脚本

3. 交叉编译(1周)
   - ARM工具链安装
   - 交叉编译程序
   - 烧录到开发板

4. 驱动开发入门(1周)
   - 字符设备驱动
   - GPIO驱动
   - 中断处理

开发板推荐

  • 树莓派4B(入门):300-500元
  • IMX6ULL开发板(进阶):500-800元

推荐资源

  • 视频:韦东山Linux驱动开发
  • 书籍:《Linux设备驱动开发详解》

2. AI基础

Python编程(2周)

# 嵌入式AI必备Python技能

1. 基础语法
   - 数据类型、控制流
   - 函数、类、模块
   
2. 科学计算库
import numpy as np
# 数组操作(AI模型的基础)
arr = np.array([1, 2, 3])
matrix = np.random.randn(3, 3)

import matplotlib.pyplot as plt
# 数据可视化
plt.plot([1, 2, 3], [4, 5, 6])

3. 数据处理
import pandas as pd
# 读取传感器数据
data = pd.read_csv('sensor_data.csv')

机器学习基础(1个月)

# 必须理解的核心概念

1. 监督学习
   - 线性回归:温度预测
   - 逻辑回归:故障分类
   - 决策树:规则推理
   - SVM:小样本分类
   
2. 非监督学习
   - K-Means:数据聚类
   - 异常检测:故障诊断

3. 深度学习入门
   - 神经网络原理
   - 前向传播、反向传播
   - 损失函数、优化器

# 示例:简单的温度预测模型
from sklearn.linear_model import LinearRegression

# 训练数据:时间 vs 温度
X = [[1], [2], [3], [4], [5]]
y = [20, 22, 24, 26, 28]

model = LinearRegression()
model.fit(X, y)

# 预测第6小时的温度
prediction = model.predict([[6]])
print(f"预测温度: {prediction[0]:.2f}°C")

推荐资源

  • 课程:吴恩达《机器学习》Coursera
  • 书籍:《机器学习实战》
  • 实践:Kaggle入门竞赛

深度学习框架(1个月)

# TensorFlow/Keras(嵌入式部署用TFLite)

1. Keras构建模型
from tensorflow import keras
from tensorflow.keras import layers

# 简单的图像分类模型
model = keras.Sequential([
    layers.Conv2D(32, 3, activation='relu', input_shape=(28, 28, 1)),
    layers.MaxPooling2D(),
    layers.Flatten(),
    layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

# 训练
model.fit(train_images, train_labels, epochs=5)

2. 模型量化(关键!)
import tensorflow as tf

# 转换为TFLite
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]  # 量化
tflite_model = converter.convert()

# 保存模型
with open('model.tflite', 'wb') as f:
    f.write(tflite_model)

3. PyTorch(可选)
import torch
import torch.nn as nn

class SimpleNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(1, 32, 3)
        self.fc = nn.Linear(32*26*26, 10)
    
    def forward(self, x):
        x = torch.relu(self.conv1(x))
        x = x.view(x.size(0), -1)
        x = self.fc(x)
        return x

推荐资源

  • 官方教程:TensorFlow官网
  • 视频:莫烦Python深度学习
  • 实践:MNIST手写数字识别

🚀 第二阶段:边缘AI技术(3-4个月)

1. TinyML核心技术

模型压缩与量化(1个月)

# 四大核心技术

1. 剪枝(Pruning)
import tensorflow_model_optimization as tfmot

# 权重剪枝
prune_low_magnitude = tfmot.sparsity.keras.prune_low_magnitude
pruning_params = {
    'pruning_schedule': tfmot.sparsity.keras.PolynomialDecay(
        initial_sparsity=0.0,
        final_sparsity=0.5,  # 剪掉50%的权重
        begin_step=0,
        end_step=1000
    )
}
model_for_pruning = prune_low_magnitude(model, **pruning_params)

2. 量化(Quantization)
# INT8量化(32位 → 8位,速度提升4倍,模型缩小4倍)
converter = tf.lite.TFLiteConverter.from_keras_model(model)

# 全整数量化
def representative_dataset():
    for _ in range(100):
        yield [np.random.randn(1, 28, 28, 1).astype(np.float32)]

converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.representative_dataset = representative_dataset
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.int8
converter.inference_output_type = tf.int8

tflite_model = converter.convert()

3. 知识蒸馏(Knowledge Distillation)
# 用大模型(教师)训练小模型(学生)
class Distiller(keras.Model):
    def __init__(self, student, teacher):
        super().__init__()
        self.teacher = teacher
        self.student = student
    
    def compile(self, optimizer, student_loss, distillation_loss, alpha=0.1):
        super().compile(optimizer=optimizer)
        self.student_loss = student_loss
        self.distillation_loss = distillation_loss
        self.alpha = alpha
    
    def train_step(self, data):
        x, y = data
        teacher_predictions = self.teacher(x, training=False)
        
        with tf.GradientTape() as tape:
            student_predictions = self.student(x, training=True)
            
            student_loss = self.student_loss(y, student_predictions)
            distillation_loss = self.distillation_loss(
                tf.nn.softmax(teacher_predictions),
                tf.nn.softmax(student_predictions)
            )
            
            loss = self.alpha * student_loss + (1 - self.alpha) * distillation_loss
        
        trainable_vars = self.student.trainable_variables
        gradients = tape.gradient(loss, trainable_vars)
        self.optimizer.apply_gradients(zip(gradients, trainable_vars))
        
        return {"loss": loss}

4. MobileNet架构
# 轻量级CNN架构(专为移动端设计)
from tensorflow.keras.applications import MobileNetV2

base_model = MobileNetV2(
    input_shape=(224, 224, 3),
    alpha=0.35,  # 宽度缩放因子(0.35 = 超轻量)
    include_top=False,
    weights='imagenet'
)

模型大小对比

原始ResNet50: 98MB
↓ 剪枝50%
49MB
↓ INT8量化
12MB
↓ 知识蒸馏到MobileNetV2
3MB ✅ 适合嵌入式部署

推荐资源

  • 论文:MobileNet、EfficientNet系列
  • 课程:TinyML Coursera(哈佛大学)
  • 工具:TensorFlow Model Optimization Toolkit

2. 嵌入式AI框架

TensorFlow Lite(重点,1.5个月)

# PC端训练 → 嵌入式推理完整流程

## Part 1: 模型训练(PC端)
import tensorflow as tf
from tensorflow import keras

# 1. 构建模型
model = keras.Sequential([
    keras.layers.Conv2D(32, 3, activation='relu', input_shape=(96, 96, 3)),
    keras.layers.MaxPooling2D(),
    keras.layers.Conv2D(64, 3, activation='relu'),
    keras.layers.MaxPooling2D(),
    keras.layers.Flatten(),
    keras.layers.Dense(128, activation='relu'),
    keras.layers.Dropout(0.5),
    keras.layers.Dense(10, activation='softmax')
])

# 2. 训练
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=10, validation_split=0.2)

# 3. 转换为TFLite
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]

# 量化感知训练(精度损失最小)
import tensorflow_model_optimization as tfmot
q_aware_model = tfmot.quantization.keras.quantize_model(model)
q_aware_model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
q_aware_model.fit(train_images, train_labels, epochs=3)

converter = tf.lite.TFLiteConverter.from_keras_model(q_aware_model)
tflite_model = converter.convert()

# 保存
with open('model_quantized.tflite', 'wb') as f:
    f.write(tflite_model)

## Part 2: 微控制器部署(STM32/ESP32)
# C++推理代码框架

// 1. 引入TFLite Micro头文件
#include "tensorflow/lite/micro/all_ops_resolver.h"
#include "tensorflow/lite/micro/micro_error_reporter.h"
#include "tensorflow/lite/micro/micro_interpreter.h"
#include "tensorflow/lite/schema/schema_generated.h"
#include "model_data.h"  // 包含.tflite模型数据

// 2. 初始化
constexpr int kTensorArenaSize = 60 * 1024;  // 60KB内存池
uint8_t tensor_arena[kTensorArenaSize];

tflite::MicroErrorReporter micro_error_reporter;
tflite::AllOpsResolver resolver;

const tflite::Model* model = tflite::GetModel(model_data);
tflite::MicroInterpreter interpreter(
    model, resolver, tensor_arena, kTensorArenaSize, &micro_error_reporter
);

interpreter.AllocateTensors();

// 3. 准备输入
TfLiteTensor* input = interpreter.input(0);
for (int i = 0; i < 96*96*3; i++) {
    input->data.int8[i] = image_data[i];  // 量化后的输入
}

// 4. 执行推理
TfLiteStatus invoke_status = interpreter.Invoke();

// 5. 读取输出
TfLiteTensor* output = interpreter.output(0);
int8_t max_score = -128;
int predicted_class = 0;
for (int i = 0; i < 10; i++) {
    if (output->data.int8[i] > max_score) {
        max_score = output->data.int8[i];
        predicted_class = i;
    }
}

printf("预测类别: %d, 置信度: %d\n", predicted_class, max_score);

实战项目:语音唤醒词识别

硬件:ESP32 + I2S麦克风
模型:1D CNN(关键词检测)
流程:
1. 采集音频(16kHz采样)
2. 提取MFCC特征(音频 → 频谱图)
3. TFLite推理
4. 检测到"Hi AI"触发唤醒

推荐资源

  • 官方:TensorFlow Lite for Microcontrollers
  • 书籍:《TinyML: Machine Learning with TensorFlow Lite》
  • 开源项目:TensorFlow Micro Examples

Edge Impulse(最简单,1个月)

# 无代码/低代码边缘AI平台

学习路线:
1. 注册Edge Impulse账号
2. 创建项目 → 数据采集
3. 设计模型(拖拽式界面)
4. 训练 → 部署到硬件

支持硬件:
- Arduino Nano 33 BLE Sense
- ESP32
- 树莓派
- STM32

典型项目:
1. 手势识别(加速度计)
   数据采集 → MFE特征 → 1D CNN → 部署

2. 关键词识别(麦克风)
   音频采集 → MFCC → 1D CNN → 检测"开灯"

3. 图像分类(摄像头)
   拍照 → MobileNetV2 → 识别物体

优势:
✅ 自动生成嵌入式代码(Arduino/C++)
✅ 内置数据增强
✅ 自动优化模型
✅ 实时性能分析

部署示例:
// Edge Impulse自动生成的Arduino代码
#include <your_project_inferencing.h>

void setup() {
    Serial.begin(115200);
}

void loop() {
    // 采集传感器数据
    float features[EI_CLASSIFIER_DSP_INPUT_FRAME_SIZE];
    get_sensor_data(features);
    
    // 运行推理
    signal_t signal;
    numpy::signal_from_buffer(features, EI_CLASSIFIER_DSP_INPUT_FRAME_SIZE, &signal);
    
    ei_impulse_result_t result;
    run_classifier(&signal, &result, false);
    
    // 输出结果
    for (int i = 0; i < EI_CLASSIFIER_LABEL_COUNT; i++) {
        Serial.printf("%s: %.2f\n", 
            result.classification[i].label, 
            result.classification[i].value
        );
    }
}

推荐资源

  • 官网:edgeimpulse.com(有免费课程)
  • YouTube:Edge Impulse官方教程
  • 社区:论坛有大量示例项目

其他框架(了解)

1. NCNN(腾讯)
   - 专为移动端优化
   - C++实现,速度极快
   - 适合Android/iOS

2. MNN(阿里)
   - 轻量级推理引擎
   - 支持多种硬件加速

3. OpenVINO(Intel)
   - 专为Intel硬件优化
   - 支持树莓派、NUC

4. CMSIS-NN(ARM)
   - ARM Cortex-M优化
   - 汇编级加速

3. 硬件加速

神经网络加速器(1个月)

# AI专用芯片/模块

1. Coral Edge TPU
   - Google设计的AI加速器
   - 4 TOPS算力(USB版本)
   - 支持TensorFlow Lite
   - 价格:60-100美元

树莓派示例:
from pycoral.utils import edgetpu
from pycoral.adapters import common

# 加载Edge TPU模型
interpreter = edgetpu.make_interpreter('model_edgetpu.tflite')
interpreter.allocate_tensors()

# 推理(比CPU快100倍)
common.set_input(interpreter, input_data)
interpreter.invoke()
output = common.output_tensor(interpreter, 0)

2. Kendryte K210
   - 0.23 TOPS算力
   - 内置卷积加速器
   - RISC-V架构
   - 价格:50-80元(国产)

开发板:Sipeed Maix系列
应用:人脸识别、物体检测

3. BL702(博流)
   - RISC-V + NPU
   - 超低功耗
   - 价格:10-20元
   
4. Jetson Nano(高端)
   - NVIDIA GPU
   - 472 GFLOPS
   - 适合复杂AI任务
   - 价格:99美元(2GB版)

FPGA加速(选学)

用Verilog/VHDL实现神经网络加速

优势:
- 可定制化硬件
- 极低延迟
- 并行计算

入门平台:
- Xilinx PYNQ-Z2(500-800元)
- Intel DE10-Nano(1000元)

学习曲线陡峭,建议有硬件基础再学

🔬 第三阶段:实战项目(2-3个月)

项目1:智能门锁人脸识别

硬件清单

- STM32H7(主控,400MHz)
- OV2640摄像头(QVGA 320x240)
- LCD屏幕(显示)
- 舵机(开锁)
- 总成本:200-300元

技术栈

1. 人脸检测:MTCNN(轻量版)
2. 人脸识别:MobileFaceNet
3. 模型量化:INT8
4. 推理引擎:TFLite Micro

性能指标:
- 检测速度:200ms/帧
- 识别准确率:95%+
- 内存占用:<512KB

完整代码框架

// main.c
#include "camera.h"
#include "lcd.h"
#include "face_detection.h"
#include "face_recognition.h"

void main() {
    // 初始化硬件
    Camera_Init();
    LCD_Init();
    FaceDetection_Init();
    FaceRecognition_Init();
    
    while(1) {
        // 1. 采集图像
        uint8_t* image = Camera_Capture();
        
        // 2. 人脸检测
        BoundingBox bbox;
        if (FaceDetection_Detect(image, &bbox)) {
            
            // 3. 裁剪人脸区域
            uint8_t face_region[112*112*3];
            CropFace(image, &bbox, face_region);
            
            // 4. 人脸识别
            int person_id = FaceRecognition_Identify(face_region);
            
            // 5. 判断是否授权
            if (IsAuthorized(person_id)) {
                UnlockDoor();
                LCD_ShowString("Welcome!");
            } else {
                LCD_ShowString("Access Denied");
            }
        }
        
        Delay_ms(100);
    }
}

// face_detection.c(TFLite推理)
#include "model_face_detection.h"

int FaceDetection_Detect(uint8_t* image, BoundingBox* bbox) {
    // 预处理:缩放到128x128
    uint8_t input[128*128*3];
    ResizeImage(image, 320, 240, input, 128, 128);
    
    // TFLite推理
    TfLiteTensor* input_tensor = interpreter->input(0);
    memcpy(input_tensor->data.int8, input, 128*128*3);
    
    interpreter->Invoke();
    
    TfLiteTensor* output = interpreter->output(0);
    // output[0]: 置信度
    // output[1-4]: bbox坐标
    
    if (output->data.f[0] > 0.9) {  // 置信度阈值
        bbox->x = output->data.f[1] * 320;
        bbox->y = output->data.f[2] * 240;
        bbox->w = output->data.f[3] * 320;
        bbox->h = output->data.f[4] * 240;
        return 1;
    }
    return 0;
}

项目2:工业设备故障预测

应用场景:电机振动异常检测

硬件

- ESP32(WiFi上传数据)
- MPU6050(加速度计)
- OLED显示屏

AI模型

# 1. 数据采集
# 采集正常运行时的振动数据(3轴加速度)
# 采集故障时的数据(轴承损坏、不平衡等)

# 2. 特征工程
import numpy as np
from scipy import signal

def extract_features(accel_data):
    """提取时域和频域特征"""
    features = []
    
    # 时域特征
    features.append(np.mean(accel_data))      # 均值
    features.append(np.std(accel_data))       # 标准差
    features.append(np.max(accel_data))       # 峰值
    features.append(np.sqrt(np.mean(accel_data**2)))  # RMS
    
    # 频域特征(FFT)
    fft = np.fft.fft(accel_data)
    freq_magnitudes = np.abs(fft)[:len(fft)//2]
    features.append(np.max(freq_magnitudes))  # 主频幅值
    features.append(np.argmax(freq_magnitudes))  # 主频频率
    
    return np.array(features)

# 3. 构建模型(1D CNN + LSTM)
from tensorflow import keras
from tensorflow.keras import layers

model = keras.Sequential([
    layers.Conv1D(32, 3, activation='relu', input_shape=(window_size, 3)),
    layers.MaxPooling1D(2),
    layers.Conv1D(64, 3, activation='relu'),
    layers.GlobalMaxPooling1D(),
    layers.Dense(64, activation='relu'),
    layers.Dropout(0.5),
    layers.Dense(3, activation='softmax')  # 3分类:正常、预警、故障
])

# 4. 量化部署
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
tflite_model = converter.convert()

ESP32推理代码

// ESP32 Arduino代码
#include <Wire.h>
#include <MPU6050.h>
#include <WiFi.h>
#include "model.h"  // TFLite模型

MPU6050 mpu;
TfLiteTensor* input;
TfLiteTensor* output;

#define WINDOW_SIZE 100
float accel_buffer[WINDOW_SIZE][3];
int buffer_index = 0;

void setup() {
    Wire.begin();
    mpu.initialize();
    WiFi.begin(ssid, password);
    
    // 初始化TFLite
    initTFLite();
}

void loop() {
    // 读取加速度
    int16_t ax, ay, az;
    mpu.getAcceleration(&ax, &ay, &az);
    
    // 归一化并存入缓冲区
    accel_buffer[buffer_index][0] = ax / 16384.0;
    accel_buffer[buffer_index][1] = ay / 16384.0;
    accel_buffer[buffer_index][2] = az / 16384.0;
    
    buffer_index++;
    
    // 缓冲区满时执行推理
    if (buffer_index >= WINDOW_SIZE) {
        // 复制到输入张量
        for (int i = 0; i < WINDOW_SIZE; i++) {
            for (int j = 0; j < 3; j++) {
                input->data.f[i*3 + j] = accel_buffer[i][j];
            }
        }
        
        // 推理
        interpreter->Invoke();
        
        // 获取结果
        float normal_prob = output->data.f[0];
        float warning_prob = output->data.f[1];
        float fault_prob = output->data.f[2];
        
        // 判断状态
        if (fault_prob > 0.8) {
            Serial.println("⚠️ 检测到故障!");
            sendAlertToCloud();
        } else if (warning_prob > 0.6) {
            Serial.println("⚡ 预警:设备异常");
        } else {
            Serial.println("✅ 运行正常");
        }
        
        buffer_index = 0;
    }
    
    delay(10);  // 100Hz采样
}

项目3:智能垃圾分类(视觉识别)

硬件

- 树莓派4B + Coral USB加速器
- 树莓派摄像头
- 舵机(控制垃圾桶盖)

技术方案

# 1. 模型训练(垃圾分类数据集)
import tensorflow as tf
from tensorflow.keras.applications import MobileNetV2

# 使用迁移学习
base_model = MobileNetV2(
    input_shape=(224, 224, 3),
    include_top=False,
    weights='imagenet'
)
base_model.trainable = False

model = tf.keras.Sequential([
    base_model,
    tf.keras.layers.GlobalAveragePooling2D(),
    tf.keras.layers.Dense(256, activation='relu'),
    tf.keras.layers.Dropout(0.5),
    tf.keras.layers.Dense(4, activation='softmax')  # 4类垃圾
])

# 2. Edge TPU转换
import tensorflow as tf

converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.representative_dataset = representative_dataset_gen
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.uint8
converter.inference_output_type = tf.uint8

tflite_model = converter.convert()

# 使用Edge TPU编译器
!edgetpu_compiler model.tflite

# 3. 树莓派部署
from picamera import PiCamera
from pycoral.utils import edgetpu
from pycoral.adapters import common, classify
import RPi.GPIO as GPIO

# 初始化
camera = PiCamera()
interpreter = edgetpu.make_interpreter('model_edgetpu.tflite')
interpreter.allocate_tensors()

SERVO_PIN = 18
GPIO.setup(SERVO_PIN, GPIO.OUT)
pwm = GPIO.PWM(SERVO_PIN, 50)

CLASSES = ['可回收', '有害垃圾', '厨余垃圾', '其他垃圾']

while True:
    # 拍照
    camera.capture('temp.jpg')
    image = Image.open('temp.jpg').resize((224, 224))
    
    # 推理(Edge TPU加速,<10ms)
    common.set_input(interpreter, image)
    interpreter.invoke()
    classes = classify.get_classes(interpreter, top_k=1)
    
    # 控制垃圾桶
    category = CLASSES[classes[0].id]
    confidence = classes[0].score
    
    if confidence > 0.8:
        print(f"识别为: {category}, 置信度: {confidence:.2%}")
        open_bin(category)  # 打开对应垃圾桶
    
    time.sleep(2)

项目4:可穿戴健康监测

硬件

- nRF52832(蓝牙低功耗芯片)
- MAX30102(心率血氧传感器)
- MPU6050(姿态传感器)
- 纽扣电池供电

AI功能

1. 心率异常检测(LSTM时序模型)
2. 跌倒检测(加速度突变识别)
3. 睡眠质量分析(多传感器融合)

核心代码

// nRF52 SDK开发
#include "nrf_delay.h"
#include "max30102.h"
#include "mpu6050.h"
#include "tflite_micro.h"

// 心率异常检测模型
#define HEART_RATE_WINDOW 60  // 60秒窗口

float hr_buffer[HEART_RATE_WINDOW];
int hr_index = 0;

void main() {
    // 初始化传感器
    MAX30102_Init();
    MPU6050_Init();
    BLE_Init();
    
    // 初始化TFLite模型
    TFLite_Init("heart_rate_model.tflite");
    
    while(1) {
        // 1. 读取心率
        uint8_t hr = MAX30102_GetHeartRate();
        hr_buffer[hr_index++] = hr;
        
        // 2. 读取加速度(跌倒检测)
        int16_t ax, ay, az;
        MPU6050_GetAccel(&ax, &ay, &az);
        
        // 检测跌倒(加速度突变)
        float accel_magnitude = sqrt(ax*ax + ay*ay + az*az);
        if (accel_magnitude > FALL_THRESHOLD) {
            SendFallAlert();
        }
        
        // 3. 心率异常检测
        if (hr_index >= HEART_RATE_WINDOW) {
            // 运行LSTM模型
            float anomaly_score = RunHeartRateModel(hr_buffer);
            
            if (anomaly_score > 0.8) {
                SendHeartRateAlert();
            }
            
            hr_index = 0;
        }
        
        // 4. 通过BLE发送数据
        BLE_SendData(hr, ax, ay, az);
        
        // 低功耗延迟
        nrf_delay_ms(1000);
    }
}

// LSTM推理(简化版)
float RunHeartRateModel(float* data) {
    // 数据归一化
    float normalized[HEART_RATE_WINDOW];
    for (int i = 0; i < HEART_RATE_WINDOW; i++) {
        normalized[i] = (data[i] - 60.0) / 40.0;  // 假设正常范围60-100
    }
    
    // TFLite推理
    TfLiteTensor* input = interpreter->input(0);
    memcpy(input->data.f, normalized, sizeof(normalized));
    
    interpreter->Invoke();
    
    TfLiteTensor* output = interpreter->output(0);
    return output->data.f[0];  // 异常概率
}

📱 第四阶段:高级专题(按需学习)

1. 端云协同

架构:
设备端(轻量模型) + 云端(复杂模型)

场景:
- 初筛在设备,详细分析在云端
- 设备资源不足时上传云端

技术栈:
- MQTT协议(设备 ↔ 云)
- AWS IoT / 阿里云IoT
- 模型热更新(OTA)

示例:
┌─────────────┐
│  ESP32设备  │
│  初筛模型   │ ──→ 99%准确率本地处理
└──────┬──────┘
       │ 不确定时上传
       ↓
┌─────────────┐
│   云服务器  │
│  完整模型   │ ──→ 99.9%准确率
└─────────────┘

2. 联邦学习

# 隐私保护的分布式训练
# 多个设备协作训练,数据不离开设备

import tensorflow_federated as tff

# 定义模型
def create_keras_model():
    return tf.keras.Sequential([
        tf.keras.layers.Dense(10, activation='relu'),
        tf.keras.layers.Dense(10, activation='softmax')
    ])

# 联邦学习流程
def model_fn():
    keras_model = create_keras_model()
    return tff.learning.from_keras_model(
        keras_model,
        input_spec=...,
        loss=tf.keras.losses.SparseCategoricalCrossentropy(),
        metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]
    )

# 多设备训练
iterative_process = tff.learning.build_federated_averaging_process(model_fn)

# 每个设备本地训练,只上传梯度
state = iterative_process.initialize()
for round_num in range(10):
    state, metrics = iterative_process.next(state, federated_train_data)
    print(f'round {round_num}, metrics={metrics}')

3. 神经架构搜索(NAS)

# 自动设计适合嵌入式的网络结构

from keras_tuner import HyperModel, RandomSearch

class MyHyperModel(HyperModel):
    def build(self, hp):
        model = keras.Sequential()
        
        # 自动搜索层数
        for i in range(hp.Int('num_layers', 1, 5)):
            model.add(layers.Conv2D(
                filters=hp.Choice(f'filters_{i}', [16, 32, 64]),
                kernel_size=3,
                activation='relu'
            ))
            model.add(layers.MaxPooling2D())
        
        model.add(layers.Flatten())
        model.add(layers.Dense(10, activation='softmax'))
        
        model.compile(
            optimizer='adam',
            loss='sparse_categorical_crossentropy',
            metrics=['accuracy']
        )
        return model

tuner = RandomSearch(
    MyHyperModel(),
    objective='val_accuracy',
    max_trials=50,
    executions_per_trial=2
)

tuner.search(train_data, train_labels, epochs=10, validation_split=0.2)

# 获取最优模型
best_model = tuner.get_best_models(num_models=1)[0]

🛠️ 工具链和开发环境

必备软件

# Python环境
conda create -n tinyml python=3.9
conda activate tinyml
pip install tensorflow==2.13
pip install tensorflow-model-optimization
pip install numpy pandas matplotlib scikit-learn

# 嵌入式开发
# STM32: STM32CubeIDE
# ESP32: Arduino IDE / ESP-IDF
# 树莓派: Raspberry Pi OS

# AI工具
pip install edge-impulse-cli
pip install pycoral  # Coral Edge TPU
pip install onnx onnxruntime  # 模型转换

# 可视化
pip install netron  # 模型结构可视化

推荐硬件采购清单

入门套件(500元):
├─ Arduino Nano 33 BLE Sense(150元)
│  内置9轴IMU、麦克风、温湿度
├─ ESP32-CAM(30元)
│  摄像头、WiFi/BT
└─ 各种传感器套装(100元)

进阶套件(1500元):
├─ STM32H7开发板(300元)
├─ OV2640摄像头(50元)
├─ Coral USB Accelerator(500元)
├─ 树莓派4B 4GB(400元)
└─ 各种模块(250元)

专业套件(5000元):
├─ Jetson Nano 4GB(700元)
├─ RealSense深度相机(2000元)
├─ Lidar传感器(1500元)
└─ 高精度IMU(800元)

📖 学习资源汇总

在线课程

  1. TinyML Coursera(哈佛大学,免费旁听)
  2. Edge AI and Computer Vision(Udacity)
  3. 嵌入式AI系统(国内:网易云课堂)

书籍

  1. 《TinyML》- Pete Warden(入门必读)
  2. 《AI at the Edge》- Daniel Situnayake
  3. 《嵌入式深度学习》(中文)

开源项目

  1. TensorFlow Examples:github.com/tensorflow/examples
  2. Edge Impulse Projects:edgeimpulse.com/projects
  3. EloquentTinyML:github.com/eloquentarduino/EloquentTinyML

论文

  1. MobileNets系列
  2. EfficientNet系列
  3. YOLO-Nano(轻量目标检测)

🎯 就业方向

岗位类型

1. 嵌入式AI工程师
   薪资:15-35K
   要求:嵌入式+深度学习

2. 边缘计算工程师
   薪资:20-40K
   要求:云计算+嵌入式AI

3. AIoT开发工程师
   薪资:18-35K
   要求:物联网+机器学习

4. 计算机视觉工程师(嵌入式方向)
   薪资:25-50K
   要求:CV算法+模型优化

5. 自动驾驶感知工程师
   薪资:30-60K
   要求:深度学习+实时系统

公司类型

  • AI芯片:地平线、寒武纪、黑芝麻
  • 智能硬件:大疆、小米、华为
  • 工业AI:海康威视、旷视、商汤
  • 自动驾驶:蔚来、小鹏、理想
  • 芯片:ARM、高通、联发科