简体   繁体   English

Rust 中的中断是否可以使用全局可变数据?

[英]Is the use of global mutable data acceptable for interrupts in Rust?

I'd like to develop an embedded system where physical button presses trigger interrupts.我想开发一个嵌入式系统,其中物理按钮按下触发中断。 I need to expose this data externally;我需要在外部公开这些数据; however to my best understand, interrupts do not generate a return nor do they take parameters as they can be called anywhere.但是据我所知,中断不会产生返回,也不会接受参数,因为它们可以在任何地方调用。

Therefore, I'd like to set a global mutable variable when an interrupt is trigger so that the button presses may be detected at a later time.因此,我想在触发中断时设置一个全局可变变量,以便以后可以检测到按钮按下。 I realize that a global mutable variable is almost always avoidable, though I wonder if this specific instance is considered acceptable.我意识到全局可变变量几乎总是可以避免的,尽管我想知道这个特定实例是否被认为是可以接受的。

This question is within the scope of Rust, which I'd like to develop for.这个问题在我想开发的 Rust 的 scope 中。

So first I should recommend that you use RTIC .所以首先我应该推荐你使用RTIC It really simplifies using interrupts.它确实简化了使用中断。 It has become many a Rust developers go-to library when dealing with interrupts.它已成为许多 Rust 开发人员在处理中断时的首选库。

There is also another library called cmim created by James Munns.还有一个名为cmim的库,由 James Munns 创建。 This is actually a nice alternative to use if you don't want to use RTIC.如果您不想使用 RTIC,这实际上是一个不错的选择。 It's also nicer to use than the static mut variable route.它也比static mut可变路由更好用。

If you want to go the static mutable variable route you'll have to do the mutex dance :如果你想 go static 可变变量路由你必须做互斥舞

static GPIO: Mutex<RefCell<Option<GPIOC>>> =
    Mutex::new( RefCell::new( None ) );

#[interrupt]
unsafe fn EXTI4( ) {
    free( | cs | { 
        if let Some( ref mut gpio ) = GPIO.borrow( cs ).borrow_mut( ).deref_mut( ) {
            // Do something useful with gpio...
        }
    } );
}

In this case, a mutable global of some kind would be needed, but there are rust-safe ways of doing so.在这种情况下,需要某种可变的全局变量,但有一些防锈的方法可以做到这一点。 Some of the embedded rust libraries have a function that borrows a global as mutable for a limited duration, which is the main way of manipulating low level registers一些嵌入式 rust 库有一个 function,它借用了一个全局变量,在有限的时间内是可变的,这是操作低级寄存器的主要方式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM