rust 嵌入式esp23 《点灯》

当你踏入 Rust 嵌入式开发的世界,控制 ESP32 单片机点亮 LED 灯并让它规律闪烁,就像与硬件进行的第一次对话。

在上一篇 rust 嵌入式esp23 《hello word》的的基础上

修改代码

添加引脚配置
rs 复制代码
use esp_hal::{
    clock::CpuClock,
    gpio::{Output, OutputConfig, Level}, //新增的引脚配置
    main,
    time::{Duration, Instant},
};
声明引脚变量

config:默认的输出引脚配置

Level::High:高电压输出

peripherals.GPIO1:绑定G1引脚

js 复制代码
    ...
    let peripherals = esp_hal::init(config);
    let config = OutputConfig::default(); //声明输出引脚默认配置
    let mut led = Output::new(peripherals.GPIO1, Level::High, config); //引脚绑定G1 并配置高电压输出
    ...
控制led灯闪烁

led.toggle():实现高低电压的切换

rs 复制代码
 ...
    loop {
        led.toggle();//切换电压输出模式
        let delay_start = Instant::now();
  ...

完整代码

rs 复制代码
#![no_std]
#![no_main]
#![deny(
    clippy::mem_forget,
    reason = "mem::forget is generally not safe to do with esp_hal types, especially those \
    holding buffers for the duration of a data transfer."
)]

use esp_hal::{
    clock::CpuClock,
    gpio::{Output, OutputConfig, Level},
    main,
    time::{Duration, Instant},
};
use esp_println::println;

#[panic_handler]
fn panic(_: &core::panic::PanicInfo) -> ! {
    loop {
        println!("111 world!");
        println!("Panic!");
    }
}

// This creates a default app-descriptor required by the esp-idf bootloader.
// For more information see: <https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/system/app_image_format.html#application-description>
esp_bootloader_esp_idf::esp_app_desc!();

#[main]
fn main() -> ! {
    // generator version: 0.5.0
    let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max());
    let peripherals = esp_hal::init(config);
    let config = OutputConfig::default();
    let mut led = Output::new(peripherals.GPIO1, Level::High, config);

    loop {
        led.toggle();
        let delay_start = Instant::now();
        while delay_start.elapsed() < Duration::from_millis(500) {}
    }

    // for inspiration have a look at the examples at https://github.com/esp-rs/esp-hal/tree/esp-hal-v1.0.0-rc.0/examples/src/bin
}
硬件连接

将led灯的一个角接G1,另外一个接GND(接地)

usb连接电脑

运行命令

shell 复制代码
cargo run 

结果如图所示

成果展示
相关推荐
q平面人7 小时前
【总工笔记】mindoc平板、桌面端笔记软件,发布到mindoc服务端
rust·tauri·华为平板·mindoc·总工笔记
MC皮蛋侠客9 小时前
Tauri 2.x 系列(九):安全模型——Capabilities、Permissions、Scope 与 CSP
rust·tauri
Source.Liu10 小时前
【Dioxus】Windows 环境下 Rust + Dioxus 安装配置笔记
windows·rust·dioxus
与你40313 小时前
CLion 中为什么要重写 _write,而不是 fputc?
嵌入式
Freak嵌入式16 小时前
MicroPython 开发避坑:用 Signal 类解决不同电路的电平兼容问题
嵌入式
zLLM_Lab16 小时前
不装 Python/PyTorch:8.1 MB Rust 程序在 MacBook Air M5 跑多模态大模型
rust
梦醒沉醉17 小时前
std1.97.1——result模块细览
rust
Thneonl19 小时前
同一资源、不同 ID:多源拓扑的 Identity Resolution
架构·rust
绍磊leo19 小时前
【保姆级】dora-rs 一键安装脚本:类ros2的fishros 风格交互菜单 + 国内镜像加速,把坑都替你踩完了
rust·dora-rs
智码看视界1 天前
Edge AI 全栈1:ESP32 传感器采集到云端大模型推理的完整链路
人工智能·物联网·嵌入式·esp32·aiot·全栈开发·edgeai