In Embassy firmware, how does a task wait for a button interrupt without polling, and which `embassy_sync` raw mutex must the shared `Signal` use?
answer
- the executor sleeps on WFE
- the handler wakes, the task resumes
- the mutex must work in a handler
- one slot, overwritten
- keep the count elsewhere
basics
~10 sThe task awaits PRESSED.wait(); the executor sleeps on WFE until the #[interrupt] handler calls PRESSED.signal(()), which wakes it. A Signal touched from a handler needs CriticalSectionRawMutex: ThreadModeRawMutex panics there and NoopRawMutex is not Sync.
solid answer
~40 s`#[embassy_executor::main]` creates the thread-mode executor and runs `main` as its first task; `#[embassy_executor::task]` declares statically allocated tasks that `main` spawns. When every task is pending, the executor executes WFE and the core sleeps. The button's `#[interrupt]` handler calls `PRESSED.signal(())` on a `static Signal`, which stores the value and wakes the task's waker; the wake executes SEV, the executor polls the task, and `PRESSED.wait().await` completes. Because a handler and a thread-mode task share the `Signal`, its raw mutex must be `CriticalSectionRawMutex`: `ThreadModeRawMutex` asserts that it is locked from thread mode and panics in the handler, and `NoopRawMutex` is not `Sync`, so the `static` fails E0277. A `Signal` holds one value, so keep the count in an `AtomicU32` and use the signal only as a wake-up.
code
rust · 43 lines#![no_std]
#![no_main]
use core::sync::atomic::{AtomicU32, Ordering};
use embassy_executor::Spawner;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::signal::Signal;
use pac::interrupt;
static PRESSES: AtomicU32 = AtomicU32::new(0);
static PRESSED: Signal<CriticalSectionRawMutex, ()> = Signal::new();
#[interrupt]
fn EXTI0() {
// clear the button's pending flag in the EXTI peripheral here
PRESSES.fetch_add(1, Ordering::Relaxed);
PRESSED.signal(()); // wakes the waiting task; never blocks
}
#[embassy_executor::task]
async fn presses() {
loop {
PRESSED.wait().await; // executor sleeps (WFE) until a wake
let n = PRESSES.swap(0, Ordering::Relaxed);
report(n);
}
}
#[embassy_executor::main]
async fn main(spawner: Spawner) {
unsafe { cortex_m::peripheral::NVIC::unmask(pac::Interrupt::EXTI0) };
spawner.spawn(presses()).unwrap();
}
#[inline(never)]
fn report(n: u32) {
unsafe { core::ptr::write_volatile(0x2000_1000 as *mut u32, n) };
}
#[panic_handler]
fn panic(_: &core::panic::PanicInfo) -> ! {
loop {}
}go deeper
Recall that an Embassy task awaits an event, and that the executor sleeps the core when no task can run.
Explain the path from interrupt handler to signal, waker, SEV and poll, and why the handler must never block.
Pick the raw mutex by execution context, know the ThreadModeRawMutex panic and the NoopRawMutex compile error, and spot the coalescing Signal.
Decide where cooperative tasks are enough and where priorities need InterruptExecutor or plain handlers, and set rules against blocking in tasks.
## How the Embassy executor waits **Embassy** is an async framework for microcontrollers. Its executor, `embassy-executor`, polls a set of tasks that are allocated statically, with no heap. On Cortex-M the common choice is the **thread-mode executor**: it runs at the lowest priority, polls every task that has been woken, and when no task can make progress it executes the **WFE** (wait for event) instruction, so the core sleeps. Waking any task executes **SEV**, which ends the WFE and makes the executor poll again. `#[embassy_executor::main]` creates this executor, defines the `main` task and runs it; `#[embassy_executor::task]` turns an `async fn` into a task that `main` spawns through the `Spawner`. Nothing polls the button in a loop. The task's future returns `Pending` at its `.await`, and only a wake brings it back. ## Wiring a raw interrupt to a task Embassy's HAL crates normally do this wiring for you: a HAL binds the interrupt with `bind_interrupts!`, and a task simply awaits a method such as `wait_for_any_edge()` on the input pin. When you write the handler yourself, a plain `#[interrupt] fn EXTI0()` from the chip's peripheral access crate works alongside Embassy, and `embassy_sync::signal::Signal` connects it to the task: 1. Declare `static PRESSED: Signal<CriticalSectionRawMutex, ()> = Signal::new();`. 2. In the handler, clear the peripheral's pending flag and call `PRESSED.signal(())`. It never blocks: it stores the value and, if a task is waiting, wakes its `Waker`. 3. In the task, loop on `PRESSED.wait().await`, which completes once a value is present and takes it out. ## Choosing the raw mutex Every `embassy_sync` primitive is generic over a **raw mutex** that decides how its internal state is protected. The choice is a soundness decision, not a tuning knob: | Raw mutex | Protects against | From an interrupt handler | |---|---|---| | `CriticalSectionRawMutex` | interrupts and other executors, via `critical_section::with` | works; documented as safe across executors and interrupts | | `ThreadModeRawMutex` | nothing but other thread-mode code; single-core only | compiles, but `lock` asserts thread mode and panics: "ThreadModeMutex can only be locked from thread mode." | | `NoopRawMutex` | nothing; one executor only | the `static` does not compile: `NoopRawMutex` is not `Sync` (E0277) | The `ThreadModeRawMutex` row is the trap: the type is `Sync`, so the `static` compiles, and the failure appears only when the button is pressed and `signal` runs in handler mode. Embassy's own examples use `ThreadModeRawMutex` for state shared between thread-mode tasks, which is where it belongs. ## A Signal is one slot `Signal` is documented as a single-slot primitive: calling `signal` while a value is already stored **overwrites** it. If three presses arrive before the task is polled, `wait()` completes once. That is right for "latest state" updates and wrong for counting. The example therefore keeps the count in a `static PRESSES: AtomicU32`, incremented with `fetch_add` in the handler and drained with `swap(0, ..)` in the task, and uses the signal only as a wake-up. When every event must be delivered, use `embassy_sync::channel::Channel` with `try_send` from the handler, and decide what to do when it is full. ## Things that break the model - **Blocking in a task.** The executor is cooperative: it regains control only when a task returns `Pending`. A busy-wait or a long computation stalls every other task on that executor, though interrupt handlers still run. - **Async locks in handlers.** `embassy_sync::mutex::Mutex::lock` returns a future; a handler cannot await it. Handlers use `Signal`, `Channel::try_send` or atomics. - **Expecting priorities from one executor.** Tasks on the thread-mode executor never preempt each other. For a higher priority, `InterruptExecutor` runs tasks inside an interrupt you dedicate to it, and higher-priority executors preempt lower ones. ## Reviewing interrupt-to-task code - Check which execution context touches each `embassy_sync` primitive, and that its raw mutex matches: anything a handler touches needs `CriticalSectionRawMutex`. - Check that the handler clears the peripheral's pending flag before returning, or the interrupt fires again at once. - Check that no event is counted through a `Signal`; counts belong in atomics or a `Channel`. - Check that no task performs a long blocking operation between two `.await` points. The server-side picture of executors, reactors and runtimes is covered with async runtimes; what is specific here is that the waker is fired by a hardware interrupt and the idle state is a sleeping core.
- Why keep the count in an `AtomicU32` instead of sending it through the `Signal`?`Signal` stores one value and each `signal` call overwrites it, so several presses between two polls of the task collapse into one wake. An atomic counter incremented in the handler and drained with `swap(0, ..)` in the task never loses a press, whatever the timing; the signal only says "look now". A `Channel` is the alternative when each event carries data that must not be dropped.
- When would you add an `InterruptExecutor`?When some async tasks need a higher priority than thread mode. It runs its tasks inside an interrupt you dedicate to it, an unused peripheral's vector or a software interrupt; you set that interrupt's priority, call `start`, which returns a `SendSpawner`, and call `on_interrupt` from the handler. Tasks on it preempt thread-mode tasks, and several interrupt executors at different priorities give several levels.
- What happens if one Embassy task runs a 50 ms busy-wait?Every other task on that executor waits 50 ms, because the executor is cooperative and regains control only when a task returns `Pending` at an `.await`. Interrupt handlers still run, so the handler's `signal` is recorded, but the woken task is not polled until the busy task yields. Replace the busy-wait with an awaited timer or move the work to its own executor.
- ThreadModeRawMutex is fine for a Signal that an interrupt handler signals.
- Signal queues every value, so three presses wake the task three times.
- The Embassy executor busy-polls all tasks in a loop.
- An embassy_sync::mutex::Mutex can be locked from inside the interrupt handler.
- Tasks on one thread-mode executor preempt each other by priority.
- A blocking loop in one task only slows that task.