使用 Rust 开发 ESP32 应用

Posted on Mon, Sep 2, 2024 单片机 Rust

ESP32 的 Rust 应用分为两种类型:

  1. 使用 std 库:可以使用 Rust 标准库的各种类型和特性,如 Vec/HashMap/Box,heap、thread/Mutex 等;
  2. 使用 core 库(non_std ): bare metal 开发;

    Github 的 esp-rs 组织中的各库命名管理:

  3. esp- 开头:是 non_std 类型,如 esp-hal;
  4. esp-idf- 开头:是 std 类型,如 esp-idf-hal;

对于 std 类型应用,cargo build 时会下载和编译依赖的 esp-idf 库。

推荐使用 cargo generate template 来创建 std/non_std 应用:

  1. std 应用:
    • cargo generate esp-rs/esp-idf-template cargo: 纯 Rust 应用(cargo-frst);
    • cargo generate esp-rs/esp-idf-template cmake: 混合 Rust and C/C++ in a traditional ESP-IDF idf.py;

  2. non_std 应用:
    • cargo generate esp-rs/esp-template

注意:

  1. 除了构建 cmake 应用外,构建纯 Rust 的 std 或 non_std 应用都只需 source ~/esp/export-esp.sh 脚本即可, 不能同时 source ~/esp/esp-idf/v5.2.1/export.sh, 否则会构建失败。
  2. 开发 Rust ESP32 应用时,需要先确定是使用 std 还是 non_std 类型,然后选择对应的 crate 库,而不是混合使用两种类型的库。
  3. std 应用可以使用 non_std 的库,但是反过来 non_std 应用只应该使用 non_std 的库

参考:The Embedded Rust ESP Development Ecosystem