Rust ESP32-C2嵌入式开发库esp32c2的使用,支持物联网设备驱动与无线通信功能

Rust ESP32-C2嵌入式开发库esp32c2的使用,支持物联网设备驱动与无线通信功能

esp32c2是一个针对Espressif ESP32-C2芯片的外设访问库(PAC)。该库基于svd2rust工具生成,提供了对ESP32-C2芯片外设的底层访问能力。

安装

在项目目录中运行以下Cargo命令:

cargo add esp32c2

或者在Cargo.toml中添加:

esp32c2 = "0.27.0"

示例代码

以下是一个使用esp32c2库进行基本GPIO控制的完整示例:

#![no_std]
#![no_main]

use esp32c2 as pac;  // 使用esp32c2 PAC
use esp_backtrace as _;
use esp_println::println;
use riscv_rt::entry;

#[entry]
fn main() -> ! {
    // 获取外设实例
    let peripherals = pac::Peripherals::take().unwrap();
    
    // 获取GPIO外设
    let gpio = peripherals.GPIO;
    
    // 配置GPIO2为输出模式
    gpio.enable.write(|w| w.enable().set_bit());
    gpio.out_en.write(|w| unsafe { w.out_en().bits(1 << 2) });
    
    // 闪烁LED
    loop {
        // 设置GPIO2高电平
        gpio.out_set.write(|w| unsafe { w.out_set().bits(1 << 2) });
        println!("GPIO2 HIGH");
        
        // 延迟
        for _ in 0..1_000_000 { riscv::asm::nop(); }
        
        // 设置GPIO2低电平
        gpio.out_clr.write(|w| unsafe { w.out_clr().bits(1 << 2) });
        println!("GPIO2 LOW");
        
        // 延迟
        for _ in 0..1_000_000 { riscv::asm::nop(); }
    }
}

无线通信功能示例

以下是一个简单的WiFi初始化示例:

use esp32c2 as pac;
use esp_wifi::initialize;

fn main() {
    let peripherals = pac::Peripherals::take().unwrap();
    
    // 初始化WiFi
    let (wifi, _) = initialize(
        peripherals.RADIO,
        peripherals.MODEM,
        &esp_wifi::configuration::Configuration::client(
            "SSID",  // 替换为你的WiFi SSID
            "PASSWORD"  // 替换为你的WiFi密码
        )
    ).unwrap();
    
    println!("WiFi initialized successfully!");
}

完整示例代码

以下是一个结合GPIO控制和WiFi功能的完整示例:

#![no_std]
#![no_main]

use esp32c2 as pac;
use esp_backtrace as _;
use esp_println::println;
use esp_wifi::initialize;
use riscv_rt::entry;

#[entry]
fn main() -> ! {
    // 获取外设实例
    let peripherals = pac::Peripherals::take().unwrap();
    
    // 初始化WiFi
    let _wifi = initialize(
        peripherals.RADIO.clone(),
        peripherals.MODEM.clone(),
        &esp_wifi::configuration::Configuration::client(
            "YOUR_SSID",
            "YOUR_PASSWORD"
        )
    ).unwrap();
    
    println!("WiFi initialized!");
    
    // 获取GPIO外设
    let gpio = peripherals.GPIO;
    
    // 配置GPIO2为输出模式
    gpio.enable.write(|w| w.enable().set_bit());
    gpio.out_en.write(|w| unsafe { w.out_en().bits(1 << 2) });
    
    // 主循环
    loop {
        // 设置GPIO2高电平
        gpio.out_set.write(|w| unsafe { w.out_set().bits(1 << 2) });
        println!("LED ON");
        
        // 延迟
        for _ in 0..1_000_000 { riscv::asm::nop(); }
        
        // 设置GPIO2低电平
        gpio.out_clr.write(|w| unsafe { w.out_clr().bits(1 << 2) });
        println!("LED OFF");
        
        // 延迟
        for _ in 0..1_000_000 { riscv::asm::nop(); }
    }
}

许可证

esp32c2库采用以下两种许可证之一:

  • Apache License, Version 2.0
  • MIT license

贡献

任何贡献都将按照上述许可证双许可,无需附加条款或条件。


1 回复

Rust ESP32-C2嵌入式开发库esp32c2的使用

介绍

esp32c2是一个针对ESP32-C2芯片的Rust嵌入式开发库,专门用于物联网设备驱动和无线通信功能的开发。该库提供了对ESP32-C2芯片各种功能的底层访问接口,包括GPIO控制、WiFi通信、定时器、中断处理等。

ESP32-C2是乐鑫推出的一款低成本、低功耗Wi-Fi微控制器,非常适合物联网应用场景。使用Rust进行开发可以充分利用其内存安全特性,避免嵌入式开发中常见的内存错误。

使用方法

添加依赖

首先在Cargo.toml中添加依赖:

[dependencies]
esp32c2 = "0.1"  # 请使用最新版本
esp32c2-hal = "0.1"

基本示例:点亮LED

#![no_std]
#![no_main]

use esp32c2_hal::{gpio::IO, pac::Peripherals, prelude::*};
use esp32c2_rt::entry;

#[entry]
fn main() -> ! {
    let peripherals = Peripherals::take().unwrap();
    let io = IO::new(peripherals.GPIO, peripherals.IO_MUX);
    
    // 将GPIO2配置为推挽输出
    let mut led = io.pins.gpio2.into_push_pull_output();
    
    loop {
        led.set_high().unwrap();  // 点亮LED
        esp32c2_hal::delay::Delay::delay_ms(1000);
        led.set_low().unwrap();   // 熄灭LED
        esp32c2_hal::delay::Delay::delay_ms(1000);
    }
}

WiFi连接示例

use esp32c2::wifi::{Wifi, WifiConfig};
use esp32c2_hal::prelude::*;

fn connect_to_wifi() -> Result<(), esp32c2::wifi::Error> {
    let peripherals = Peripherals::take().unwrap();
    let mut wifi = Wifi::new(peripherals.WIFI);
    
    let config = WifiConfig {
        ssid: "your_wifi_ssid".into(),
        password: "your_wifi_password".into(),
        ..Default::default()
    };
    
    wifi.connect(&config)?;
    
    while !wifi.is_connected() {
        // 等待连接完成
    }
    
    println!("Connected to WiFi!");
    Ok(())
}

定时器中断示例

use esp32c2_hal::{pac, timer::TimerGroup, interrupt};
use esp32c2_rt::entry;

#[entry]
fn main() -> ! {
    let peripherals = pac::Peripherals::take().unwrap();
    let timer_group0 = TimerGroup::new(peripherals.TIMG0, &clocks);
    let mut timer0 = timer_group0.timer0;
    
    // 设置定时器中断,每秒触发一次
    timer0.start(1u64.secs());
    timer0.listen();
    
    unsafe {
        interrupt::enable(pac::Interrupt::TIMG0_T0_LEVEL, interrupt::Priority::Priority1).unwrap();
    }
    
    loop {}
}

#[interrupt]
fn TIMG0_T0_LEVEL() {
    println!("Timer interrupt triggered!");
    
    // 清除中断标志
    let peripherals = unsafe { pac::Peripherals::steal() };
    let timer_group0 = TimerGroup::new(peripherals.TIMG0, &clocks);
    timer_group0.timer0.clear_interrupt();
}

完整示例:GPIO中断与WiFi结合应用

#![no_std]
#![no_main]

use esp32c2::wifi::{Wifi, WifiConfig};
use esp32c2_hal::{
    gpio::{IO, Interrupt, Pin},
    interrupt,
    pac::{self, Peripherals},
    prelude::*,
    timer::TimerGroup,
};
use esp32c2_rt::entry;

static mut WIFI_CONNECTED: bool = false;

#[entry]
fn main() -> ! {
    let peripherals = Peripherals::take().unwrap();
    
    // 初始化GPIO
    let io = IO::new(peripherals.GPIO, peripherals.IO_MUX);
    let mut button = io.pins.gpio0.into_pull_up_input();
    button.listen(Interrupt::NegEdge); // 下降沿触发中断
    
    // 初始化定时器
    let timer_group0 = TimerGroup::new(peripherals.TIMG0, &clocks);
    let mut timer0 = timer_group0.timer0;
    timer0.start(5u64.secs()); // 5秒定时器
    timer0.listen();
    
    // 初始化WiFi
    let mut wifi = Wifi::new(peripherals.WIFI);
    let config = WifiConfig {
        ssid: "your_wifi_ssid".into(),
        password: "your_wifi_password".into(),
        ..Default::default()
    };
    
    // 启用中断
    unsafe {
        interrupt::enable(pac::Interrupt::GPIO, interrupt::Priority::Priority1).unwrap();
        interrupt::enable(pac::Interrupt::TIMG0_T0_LEVEL, interrupt::Priority::Priority2).unwrap();
    }
    
    // 主循环
    loop {
        if unsafe { WIFI_CONNECTED } {
            // 执行需要WiFi连接的任务
        }
    }
}

#[interrupt]
fn GPIO() {
    let peripherals = unsafe { pac::Peripherals::steal() };
    let io = IO::new(peripherals.GPIO, peripherals.IO_MUX);
    let button = io.pins.gpio0;
    
    if button.is_low().unwrap() {
        println!("Button pressed!");
        // 处理按钮按下事件
    }
    
    button.clear_interrupt();
}

#[interrupt]
fn TIMG0_T0_LEVEL() {
    let peripherals = unsafe { pac::Peripherals::steal() };
    let timer_group0 = TimerGroup::new(peripherals.TIMG0, &clocks);
    timer_group0.timer0.clear_interrupt();
    
    println!("5 seconds elapsed, checking WiFi...");
    // 定时检查WiFi状态
}

主要功能

  1. GPIO控制:数字输入/输出、中断处理
  2. WiFi通信:STA/AP模式、扫描网络、连接管理
  3. 定时器:硬件定时器、看门狗定时器
  4. PWM:LED控制、电机驱动
  5. ADC:模拟信号采集
  6. I2C/SPI/UART:外设通信接口

开发环境配置

  1. 安装Rust工具链:rustup install nightly
  2. 添加目标平台:rustup target add riscv32imc-unknown-none-elf
  3. 安装cargo-generate:cargo install cargo-generate
  4. 使用esp-template创建项目:cargo generate --git https://github.com/esp-rs/esp-template

注意事项

  1. 该库主要面向no_std环境
  2. 需要配合esp32c2-rt运行时使用
  3. 某些功能可能需要特定的硬件配置
  4. WiFi功能使用时需注意电源管理

通过这个库,开发者可以充分利用Rust的安全特性来开发ESP32-C2的嵌入式应用,特别是物联网设备相关的功能实现。

回到顶部