esp32c3 运行 Rust(一)
上篇已经搭建好开发环境,现在开始点亮板载的 LED。
环境
-
OS: Ubuntu 20.04.4 LTS
-
Rust: rustc 1.62.0-nightly
-
IDE: VsCode
-
ESP32C3: ESP-C3-13-Kit 开发板
LED GPIO R GPIO3 G GPIO4 B GPIO5
创建项目
使用如下命令创建 blink 项目,并修改项目配置
cargo generate --git https://github.com/esp-rs/esp-idf-template cargo
创建细节参见 esp32c3 运行 Rust(〇) 中 创建项目 HelloWorld。
点亮 LED
-
安装相关依赖
在
Cargo.toml中添加相关依赖- embedded-hal 嵌入式系统的硬件抽象层
- esp-idf-hal ESP32[-XX] + ESP-IDF 的
embedded-hal实现
# ... [dependencies] # ... esp-idf-sys = { version = "0.31.1", features = ["binstart"] } embedded-hal = "0.2.7" # 添加这行 esp-idf-hal = "0.36.0" # 添加这行 # ... -
引入相关依赖
在
src/main.rs中添加如下内容use embedded_hal::digital::v2::OutputPin; use esp_idf_hal::peripherals::Peripherals; -
控制 LED 小灯
fn main() { use esp_idf_sys as _; // If using the `binstart` feature of `esp-idf-sys`, always keep let peripherals = Peripherals::take().unwrap(); let mut led = peripherals.pins.gpio3.into_output().unwrap(); // 红色 LED 小灯接在 GIPO3 上 led.set_high().unwrap(); println!("LED on!"); } -
编译并上传
连接开发板,使用如下命令编译并上传
cargo espflash --release --monitor /dev/ttyUSB0
让 LED 闪烁起来
引入标准库中修改模块
use std::{
thread,
time::Duration,
};
修改 main 方法
// ...
// 移除以下两行代码
led.set_high().unwrap();
println!("LED on!");
// 添加如下代码
loop {
println!("LED on");
led.set_high().unwrap();
thread::sleep(Duration::from_millis(1000));
led.set_low().unwrap();
println!("LED off");
thread::sleep(Duration::from_millis(1000));
}
重新编译上传,没有报错的情况下,将看到 LED 闪烁起来了。
完整代码如下
use esp_idf_sys as _; // If using the `binstart` feature of `esp-idf-sys`, always keep this module imported
use std::{
thread,
time::Duration,
};
use esp_idf_hal::peripherals::Peripherals;
use embedded_hal::digital::v2::OutputPin;
fn main() {
// Temporary. Will disappear once ESP-IDF 4.4 is released, but for now it is necessary to call this function once,
// or else some patches to the runtime implemented by esp-idf-sys might not link properly.
esp_idf_sys::link_patches();
let peripherals = Peripherals::take().unwrap();
let mut led = peripherals.pins.gpio3.into_output().unwrap();
loop {
println!("LED on");
led.set_high().unwrap();
thread::sleep(Duration::from_millis(1000));
led.set_low().unwrap();
println!("LED off");
thread::sleep(Duration::from_millis(1000));
}
}
使用 esp_idf_hal 库中的 toggle 方法控制 LED 闪烁
use esp_idf_sys as _; // If using the `binstart` feature of `esp-idf-sys`, always keep this module imported
use std::{
thread,
time::Duration,
};
use embedded_hal::digital::v2::ToggleableOutputPin;
use esp_idf_hal::peripherals::Peripherals;
fn main() {
// Temporary. Will disappear once ESP-IDF 4.4 is released, but for now it is necessary to call this function once,
// or else some patches to the runtime implemented by esp-idf-sys might not link properly.
esp_idf_sys::link_patches();
let peripherals = Peripherals::take().unwrap();
let mut led = peripherals.pins.gpio3.into_output().unwrap();
loop {
led.toggle().unwrap();
thread::sleep(Duration::from_millis(1000));
}
}