1. 环境搭建与Hello World
任务目标
在嵌入式开发板上编译并运行TFLite Micro自带的hello world示例,通过串口输出连续递增的数值,验证TensorFlow Lite Micro开发环境(工具链、依赖库、编译流程)配置正确。
环境依赖
- Linux主机(Ubuntu 20.04+)或macOS
- GCC交叉编译工具链(针对目标板架构)
- 目标开发板:SparkFun Edge、STM32F746G Discovery或ESP32(任选其一)
- 串口终端工具(minicom/picocom)
- TFLite Micro源码(
git clone https://github.com/tensorflow/tflite-micro.git)
关键完整代码
hello world示例的核心逻辑位于tflite-micro/tensorflow/lite/micro/examples/hello_world目录。以下为main.cc的完整实现(以SparkFun Edge为例):
#include "tensorflow/lite/micro/examples/hello_world/main_functions.h"
int main(int argc, char* argv[]) {
setup();
while (true) {
loop();
}
}
实际推理逻辑在main_functions.cc中:
#include "tensorflow/lite/micro/examples/hello_world/main_functions.h"
#include "tensorflow/lite/micro/examples/hello_world/model.h"
#include "tensorflow/lite/micro/micro_interpreter.h"
#include "tensorflow/lite/micro/micro_mutable_op_resolver.h"
#include "tensorflow/lite/schema/schema_generated.h"
constexpr int kTensorArenaSize = 2 * 1024;
uint8_t tensor_arena[kTensorArenaSize];
void setup() {
// 加载模型
const tflite::Model* model = tflite::GetModel(g_model);
// 注册算子(仅需FullyConnected)
static tflite::MicroMutableOpResolver<1> resolver;
resolver.AddFullyConnected();
// 构建解释器
static tflite::MicroInterpreter interpreter(
model, resolver, tensor_arena, kTensorArenaSize);
interpreter.AllocateTensors();
}
void loop() {
// 获取输入张量并写入固定值
TfLiteTensor* input = interpreter.input(0);
input->data.f[0] = 0.0f;
// 执行推理
interpreter.Invoke();
// 读取输出(正弦预测值)
TfLiteTensor* output = interpreter.output(0);
float y_pred = output->data.f[0];
// 通过串口打印结果
printf("x: 0.0, y_pred: %f\n", y_pred);
}
编译与烧录
在源码根目录执行以下命令(以SparkFun Edge为例):
make -f tensorflow/lite/micro/tools/make/Makefile \
TARGET=sparkfun_edge \
hello_world_bin
编译产物位于tensorflow/lite/micro/tools/make/gen/sparkfun_edge_x86_64/bin/目录。使用开发板对应的烧录工具(如JLinkExe或openocd)将hello_world.bin写入板卡。
验证方法
- 用USB线连接开发板与主机,确认串口设备(如
/dev/ttyUSB0)存在 - 打开串口终端:
picocom /dev/ttyUSB0 -b 115200 - 复位开发板,观察串口输出
通过条件:串口持续输出形如x: 0.0, y_pred: 0.0的数值行,且数值在-1.0到1.0范围内变化。若输出稳定且无报错,说明模型加载成功、算子注册正确、推理链路完整,环境配置通过验证。
常见问题
- 编译报错找不到头文件:确认在tflite-micro根目录执行make命令,且未修改目录结构
- 烧录后无输出:检查串口波特率是否为115200,确认开发板供电正常
- 输出乱码:检查串口连接线是否为交叉线,或尝试更换USB端口