rtic/examples/late-resources.rs

88 lines
2.5 KiB
Rust
Raw Permalink Normal View History

2017-09-04 23:31:14 +02:00
//! Demonstrates initialization of resources in `init`.
#![deny(unsafe_code)]
#![deny(warnings)]
2017-09-04 23:31:14 +02:00
#![feature(proc_macro)]
#![no_std]
extern crate cortex_m_rtfm as rtfm;
extern crate stm32f103xx;
use rtfm::{app, Threshold};
app! {
device: stm32f103xx,
resources: {
// Usually, resources are initialized with a constant initializer:
static ON: bool = false;
2017-11-22 09:27:14 +01:00
// However, there are cases where this is not possible or not desired.
// For example, there may not be a sensible value to use, or the type may
// not be constructible in a constant (like `Vec`).
2017-09-04 23:31:14 +02:00
//
2017-11-22 09:27:14 +01:00
// While it is possible to use an `Option` in some cases, that requires
// you to properly initialize it and `.unwrap()` it at every use. It
// also consumes more memory.
//
// To solve this, it is possible to defer initialization of resources to
// `init` by omitting the initializer. Doing that will require `init` to
// return the values of all "late" resources.
2017-09-04 23:31:14 +02:00
static IP_ADDRESS: u32;
2017-11-22 09:27:14 +01:00
// PORT is used by 2 tasks, making it a shared resource. This just tests
// another internal code path and is not important for the example.
static PORT: u16;
2017-09-04 23:31:14 +02:00
},
idle: {
// Test that late resources can be used in idle
resources: [IP_ADDRESS],
2017-10-02 15:11:37 +02:00
},
2017-09-04 23:31:14 +02:00
tasks: {
SYS_TICK: {
priority: 1,
2017-09-04 23:31:14 +02:00
path: sys_tick,
resources: [IP_ADDRESS, PORT, ON],
2017-09-04 23:31:14 +02:00
},
EXTI0: {
priority: 2,
path: exti0,
resources: [PORT],
}
2017-09-04 23:31:14 +02:00
}
}
// The signature of `init` is now required to have a specific return type.
fn init(_p: init::Peripherals, _r: init::Resources) -> init::LateResources {
2017-11-22 09:27:14 +01:00
// `init::Resources` does not contain `IP_ADDRESS`, since it is not yet
// initialized.
2017-09-04 23:31:14 +02:00
//_r.IP_ADDRESS; // doesn't compile
// ...obtain value for IP_ADDRESS from EEPROM/DHCP...
let ip_address = 0x7f000001;
init::LateResources {
2017-11-22 09:27:14 +01:00
// This struct will contain fields for all resources with omitted
// initializers.
2017-09-04 23:31:14 +02:00
IP_ADDRESS: ip_address,
PORT: 0,
2017-09-04 23:31:14 +02:00
}
}
fn sys_tick(_t: &mut Threshold, r: SYS_TICK::Resources) {
2017-11-22 09:27:14 +01:00
// Other tasks can access late resources like any other, since they are
// guaranteed to be initialized when tasks are run.
2017-09-04 23:31:14 +02:00
r.IP_ADDRESS;
}
fn exti0(_t: &mut Threshold, _r: EXTI0::Resources) {}
2017-10-02 15:11:37 +02:00
fn idle(_t: &mut Threshold, _r: idle::Resources) -> ! {
2017-09-04 23:31:14 +02:00
loop {
rtfm::wfi();
}
}