aboutsummaryrefslogtreecommitdiff
path: root/examples/async_systick3.rs
blob: 999ad2762780d35792b40822d8a583bf8ea19960 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
//! examples/async_task2
#![no_main]
#![no_std]
#![feature(const_fn)]
#![feature(type_alias_impl_trait)]

// use core::cell::Cell;
// use core::cell::UnsafeCell;
use core::future::Future;
use core::mem;
// use core::mem::MaybeUninit;
use core::pin::Pin;
// use core::ptr;
// use core::ptr::NonNull;
// use core::sync::atomic::{AtomicPtr, AtomicU32, Ordering};
use core::task::{Context, Poll, Waker};
use rtic::async_util::Task;

use cortex_m_semihosting::{debug, hprintln};

use panic_semihosting as _;
use rtic::Mutex;

#[rtic::app(device = lm3s6965, dispatchers = [SSI0])]
mod app {
    use crate::*;

    #[resources]
    struct Resources {
        systick: Systick,
    }

    #[init]
    fn init(cx: init::Context) -> init::LateResources {
        hprintln!("init").ok();
        foo::spawn().unwrap();
        init::LateResources {
            systick: Systick {
                syst: cx.core.SYST,
                state: State::Done,
                queue: BinaryHeap::new(),
                // waker: None,
            },
        }
    }

    #[idle]
    fn idle(_: idle::Context) -> ! {
        let mut i = 0;
        loop {
            i += 1;
            hprintln!("idle {}", i).ok();
            if i == 3 {
                debug::exit(debug::EXIT_SUCCESS);
            }
            cortex_m::asm::wfi(); // put the MCU in sleep mode until interrupt occurs
        }
    }

    #[task(resources = [systick])]
    async fn foo(cx: foo::Context) {
        hprintln!("foo task").ok();
        let mut systick = cx.resources.systick;

        hprintln!("delay long time").ok();
        timer_delay(&mut systick, 5000000).await;

        hprintln!("delay short time").ok();
        timer_delay(&mut systick, 1000000).await;
        hprintln!("foo task resumed").ok();
    }

    // RTIC task bound to the HW SysTick interrupt
    #[task(binds = SysTick, resources = [systick], priority = 2)]
    fn systic(mut cx: systic::Context) {
        hprintln!("systic interrupt").ok();
        cx.resources.systick.lock(|s| {
            s.syst.disable_interrupt();
            s.state = State::Done;
            s.queue.pop().map(|w| w.waker.wake());
            if let Some(w) = s.queue.peek() {
                s.syst.set_reload(w.time);
            } else {
                s.syst.disable_interrupt();
            }
        });
    }
}

//=============
// Timer
// Later we want a proper queue

//use core::cmp::{Ord, Ordering, PartialOrd};
use core::cmp::Ordering;
use heapless::binary_heap::{BinaryHeap, Max};
use heapless::consts::U8;
// use heapless::Vec;

pub enum State {
    Started,
    Done,
}

struct Timeout {
    time: u32,
    waker: Waker,
}

impl Ord for Timeout {
    fn cmp(&self, other: &Self) -> Ordering {
        self.time.cmp(&other.time)
    }
}

impl PartialOrd for Timeout {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(&other))
    }
}

impl PartialEq for Timeout {
    fn eq(&self, other: &Self) -> bool {
        self.time == other.time
    }
}

impl Eq for Timeout {}

pub struct Systick {
    syst: cortex_m::peripheral::SYST,
    state: State,
    queue: BinaryHeap<Timeout, U8, Max>,
}

//=============
// Timer
// Later we want a proper queue

pub struct Timer<'a, T: Mutex<T = Systick>> {
    request: Option<u32>,
    systick: &'a mut T,
}

impl<'a, T: Mutex<T = Systick>> Future for Timer<'a, T> {
    type Output = ();
    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let Self { request, systick } = &mut *self;
        systick.lock(|s| {
            // enqueue a new request
            request.take().map(|t| {
                s.syst.set_reload(t);
                s.syst.enable_counter();
                s.syst.enable_interrupt();
                s.state = State::Started;
                s.queue
                    .push(Timeout {
                        time: t,
                        waker: cx.waker().clone(),
                    })
                    .ok();
            });

            match s.state {
                State::Done => Poll::Ready(()),
                State::Started => Poll::Pending,
            }
        })
    }
}

fn timer_delay<'a, T: Mutex<T = Systick>>(systick: &'a mut T, t: u32) -> Timer<'a, T> {
    hprintln!("timer_delay {}", t).ok();
    Timer {
        request: Some(t),
        systick,
    }
}