# 采集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)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)// 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上顯示
}