esp32c3 运行 Rust(〇)

2,932 阅读2分钟

esp32c3 运行 Rust(〇)

ESP32-C3 是一款安全稳定、低功耗、低成本的物联网芯片,搭载 RISC-V 32 位单核处理器,支持 2.4 GHz Wi-Fi 和 Bluetooth 5 (LE),为物联网产品提供行业领先的射频性能、完善的安全机制和丰富的内存资源。ESP32-C3 对 Wi-Fi 和 Bluetooth 5 (LE) 的双重支持降低了设备配网难度,适用于广泛的物联网应用场景。

环境

  • OS: Ubuntu 20.04.4 LTS

  • Rust: rustc 1.62.0-nightly

  • IDE: VsCode

  • ESP32C3: ESP-C3-13-Kit 开发板

    image.png image.png

安装相关工具链

安装 Rust

通过如下命令安装 Rust

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

ESP32C3 使用 nightly 版本的 Rust,通过 rustup 安装 nightly 版本的工具链。

rustup install nightly
rustup component add rust-src --toolchain nightly

安装 ESP32 相关工具链

  • cargo-generate 创建项目向导
  • cargo-espflash 烧写固件
  • espmonitor 查看固件日志
  • bindgen 为 C API 生成 Rust 绑定
  • ldproxy 乐鑫构建工具链依赖

使用如下命令安装

cargo install cargo-generate cargo-espflash espmonitor bindgen ldproxy

安装系统依赖

sudo apt install llvm-dev libclang-dev clang

解决安装报错

安装时可能会遇到相关的系统依赖没有安装造成的安装失败。

  • error: linker `cc` not found

    Cargo 找不到 cc 编译器程序来编译应用程序。由于 Rust 还没有包含自己的链接器,因此您需要安装一个像 gcc 这样的 C 编译器来充当链接器。

    sudo apt install build-essential
    
  • 其他的错误 error: failed to run custom build command for libudev-sys v0.1.4

    sudo apt update && sudo apt install -y vim nano git curl gcc ninja-build cmake libudev-dev python3 python3-pip libusb-1.0-0 libssl-dev pkg-config libtinfo5
    

创建项目 HelloWorld

cargo generate --git https://github.com/esp-rs/esp-idf-template cargo
  1. 项目配置

    • Project Name(项目名称):hello-world
    • Rust toolchain: nightly
    • MCU: esp32c3
    • STD support: true
    • ESP-IDF native build version: v4.4
  2. 进入项目

    cd hello-world
    
  3. 修改项目配置

    • Cargo.toml

      #...
      [features]
      pio = ["esp-idf-sys/pio"]
      #...
      

      改为

      #...
      [features]
      default = ["native"]
      native = ["esp-idf-sys/native"]
      #...
      
    • .cargo/config.toml

      在文件末尾添加如下内容,让当前项目使用全局的 espressif 工具链,而不是每个项目安装自己的 espressif 工具链(毕竟该工具链需要 10GB 以上的空间~^o^~)。

      ESP_IDF_TOOLS_INSTALL_DIR = { value = "global" }
      
  4. 编译并上传固件

    cargo espflash --release --monitor /dev/ttyUSB0
    

    遇到如下错误

    Serial port: /dev/ttyUSB0
    Connecting...
    
    Error: espflash::serial_error
    
      × Failed to open serial port /dev/ttyUSB0
      ├─▶ Error while connecting to device
      ├─▶ IO error while using serial port: Permission denied
      ╰─▶ Permission denied
    
     执行如下命令,重启终端
    
    sudo usermod -a -G dialout <username>
    
  5. 结果

    (...)
    I (284) sleep: Enable automatic switching of GPIO sleep configuration
    I (292) cpu_start: Starting scheduler.
    Hello, world!
    

至此,rust 已经运行在 ESP32C3 上了。

参考

Embedded Rust on Espressif