Rust is a great option for embedded computing, especially for small devices like ESP32.
There is a very inexpensive dev board, called ESP32-C3 Super Mini which sells for ~$2 on AliExpress.
The chip is RISC-based, supports Wifi & Bluetooth, and includes a built-in LED - which we'll use in this project.
Installing Rust
First you'll need Rust on your machine.
The toolchain can be installed via Rustup, or (my preferred way) using asdf
.
TIP: asdf
is a great way to manage multiple versions of programming language tools.
To install with asdf
:
# add rust plugin
asdf plugin-add rust https://github.com/asdf-community/asdf-rust.git
# install rust
asdf install rust 1.81.0
# set default version
asdf global rust 1.81.0
Create the project
Let's create the project folder structure.
We can start with the template:
$> cargo generate esp-rs/esp-idf-template cargo
⚠️ Favorite `esp-rs/esp-idf-template` not found in config, using it as a git repository: https://github.com/esp-rs/esp-idf-template.git
🤷 Project Name: blink
🔧 Destination: some/path/blink ...
🔧 project-name: blink ...
🔧 Generating template ...
✔ 🤷 Which MCU to target? · esp32c3
✔ 🤷 Configure advanced template options? · false
🔧 Moving generated files into: `some/path/blink`...
🔧 Initializing a fresh Git repository
✨ Done! New project created some/path/blink
We'll need access to the HAL (hardware abstraction layer), so install the esp-idf-hal
crate too:
cd blink
cargo add esp-idf-hal
The Code
Now add this to src/main.rs
to blink the LED:
use esp_idf_hal::delay::FreeRtos;
use esp_idf_hal::gpio::*;
use esp_idf_hal::peripherals::Peripherals;
use log::info;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// enable logging
esp_idf_svc::log::EspLogger::initialize_default();
// get peripherals
let peripherals = Peripherals::take()?;
// built-in LED is GPIO8
let mut led = PinDriver::output(peripherals.pins.gpio8)?;
// alternate between high and low, with delay of 1s
loop {
info!("high");
led.set_high()?;
FreeRtos::delay_ms(1000);
info!("low");
led.set_low()?;
FreeRtos::delay_ms(1000);
}
}
Running the code
Connect the dev board to USB, and then flash it with:
cargo run
The LED should now be blinking, and the message "HIGH"/"LOW" will be displayed in the terminal.
Happy hacking ✌️
P.S. Here's the source code:
https://github.com/joshnuss/esp-blink-rs
Top comments (0)