//! embassy hello world
//!
//! This is an example of running the embassy executor with multiple tasks
//! concurrently.
//% CHIPS: esp32 esp32c2 esp32c3 esp32c6 esp32h2 esp32s2 esp32s3
//% FEATURES: embassy esp-hal-embassy/integrated-timers
#![no_std]
#![no_main]
#![feature(type_alias_impl_trait)]
use embassy_executor::Spawner;
use embassy_time::{Duration, Timer, Instant};
use esp_backtrace as _;
use esp_hal::{
prelude::*,
clock::ClockControl,
peripherals::Peripherals,
system::SystemControl,
timer::{timg::TimerGroup, ErasedTimer, OneShotTimer},
gpio::{Io, Pull, Level, AnyInput, AnyOutput},
};
use esp_println::println;
use static_cell::StaticCell;
struct DistanceSenor {
trigger: AnyOutput<'static>,
echo: AnyInput<'static>
}
// When you are okay with using a nightly compiler it's better to use https://docs.rs/static_cell/2.1.0/static_cell/macro.make_static.html
macro_rules! mk_static {
($t:ty,$val:expr) => {{
static STATIC_CELL: StaticCell<$t> = StaticCell::new();
#[deny(unused_attributes)]
let x = STATIC_CELL.uninit().write(($val));
x
}};
}
#[embassy_executor::task]
async fn sense_distance(mut distance_sensor: DistanceSenor) {
loop {
println!("Checking distance");
distance_sensor.trigger.set_high();
Timer::after(Duration::from_micros(10)).await;
distance_sensor.trigger.set_low();
distance_sensor.echo.wait_for_rising_edge().await;
let echo_high_start = Instant::now();
distance_sensor.echo.wait_for_falling_edge().await;
let echo_dur = Instant::now().duration_since(echo_high_start).as_micros();
println!("Distance: {:.3}cm", (echo_dur as f64 * 0.017));
Timer::after(Duration::from_secs(2)).await;
}
}
#[main]
async fn main(spawner: Spawner) {
println!("Init!");
let peripherals = Peripherals::take();
let system = SystemControl::new(peripherals.SYSTEM);
let clocks = ClockControl::boot_defaults(system.clock_control).freeze();
let io = Io::new(peripherals.GPIO, peripherals.IO_MUX);
let timg0 = TimerGroup::new(peripherals.TIMG0, &clocks, None);
let timer0: ErasedTimer = timg0.timer0.into();
let timers = [OneShotTimer::new(timer0)];
let timers = mk_static!([OneShotTimer<ErasedTimer>; 1], timers);
esp_hal_embassy::init(&clocks, timers);
let mut distance_sensor = DistanceSenor {
trigger: AnyOutput::new(io.pins.gpio15, Level::Low),
echo: AnyInput::new(io.pins.gpio16, Pull::Up),
};
spawner.spawn(sense_distance(distance_sensor)).ok();
loop {
println!("Bing!");
Timer::after(Duration::from_millis(5_000)).await;
}
}