Keil MDK 5.38+ TensorFlow Lite Micro源码 CMSIS-NN库
用Python生成训练数据:
# 采集MPU6050数据(加速度计X/Y/Z轴)import numpy as np
from sklearn.model_selection import train_test_split
# 模拟3种手势数据(挥手/握拳/静止)
gestures = {
"wave": np.random.randn(1000, 3) * 0.5 + [1, 0, 0],
"fist": np.random.randn(1000, 3) * 0.5 + [0, 1, 0],
"idle": np.random.randn(1000, 3) * 0.2 + [0, 0, 1]
}
X = np.vstack(gestures.values())
y = np.repeat([0, 1, 2], 1000) # 标签
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
训练TensorFlow Lite Micro模型:
import tensorflow as tf
model = tf.keras.Sequential([
tf.keras.layers.Dense(8, activation='relu', input_shape=(3,)),
tf.keras.layers.Dense(3, activation='softmax')
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy')
model.fit(X_train, y_train, epochs=50)
# 转换为TFLite Micro格式
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
tflite_model = converter.convert()
with open('gesture_model.tflite', 'wb') as f:
f.write(tflite_model)
将 .tflite 模型转换为C数组: 关键代码实现:
// main.c#include "tensorflow/lite/micro/all_ops_resolver.h"#include "tensorflow/lite/micro/micro_error_reporter.h"#include "tensorflow/lite/micro/micro_interpreter.h"#include "model_data.h" // 生成的模型头文件// 初始化TFLite Microstatic tflite::MicroInterpreter static_interpreter(
tflite::GetModel(g_model),
tflite::AllOpsResolver(),
tensor_arena,
kTensorArenaSize);
// 读取MPU6050数据并推理void run_inference(float* input_data) {
TfLiteTensor* input = static_interpreter.input(0);
memcpy(input->data.f, input_data, 3 * sizeof(float));
static_interpreter.Invoke();
TfLiteTensor* output = static_interpreter.output(0);
uint8_t gesture_id = argmax(output->data.f, 3); // 获取预测结果
display_result(gesture_id); // 在OLED上显示
}
量化压缩:将模型从FP32转为INT8,体积减少75% 硬件加速:启用STM32H743的DSP指令集,推理速度提升2倍 多任务调度:用FreeRTOS管理传感器数据采集和AI推理
END