cortex_m_rt

Attribute Macro interrupt

Source
#[interrupt]
Expand description

Attribute to declare an interrupt (AKA device-specific exception) handler

NOTE: This attribute is exposed by cortex-m-rt only when the device feature is enabled. However, that export is not meant to be used directly – using it will result in a compilation error. You should instead use the PAC (usually generated using svd2rust) re-export of that attribute. You need to use the re-export to have the compiler check that the interrupt exists on the target device.

§Syntax

extern crate device;

// the attribute comes from the PAC not from cortex-m-rt
use device::interrupt;

#[interrupt]
fn USART1() {
    // ..
}

where the name of the function must be one of the device interrupts.

§Usage

#[interrupt] fn Name(.. overrides the default handler for the interrupt with the given Name. These handlers must have signature [unsafe] fn() [-> !]. It’s possible to add state to these handlers by declaring static mut variables at the beginning of the body of the function. These variables will be safe to access from the function body.

If the interrupt handler has not been overridden it will be dispatched by the default exception handler (DefaultHandler).

§Properties

Interrupts handlers can only be called by the hardware. Other parts of the program can’t refer to the interrupt handlers, much less invoke them as if they were functions.

static mut variables declared within an interrupt handler are safe to access and can be used to preserve state across invocations of the handler. The compiler can’t prove this is safe so the attribute will help by making a transformation to the source code: for this reason a variable like static mut FOO: u32 will become let FOO: &mut u32;.

§Examples

  • Using state within an interrupt handler
extern crate device;

use device::interrupt;

#[interrupt]
fn TIM2() {
    static mut COUNT: i32 = 0;

    // `COUNT` is safe to access and has type `&mut i32`
    *COUNT += 1;

    println!("{}", COUNT);
}