From 2655c56659bee3910c6447ada3529ad5dc25fef6 Mon Sep 17 00:00:00 2001
From: Josef Utbult <josutb-7@student.ltu.se>
Date: Tue, 23 Mar 2021 16:27:53 +0100
Subject: [PATCH] bare9_2

---
 examples/rtic_bare9.rs | 51 +++++++++++++++++++++++++++++++++++-------
 1 file changed, 43 insertions(+), 8 deletions(-)

diff --git a/examples/rtic_bare9.rs b/examples/rtic_bare9.rs
index 62c0b11..e629c2a 100644
--- a/examples/rtic_bare9.rs
+++ b/examples/rtic_bare9.rs
@@ -24,6 +24,9 @@ const APP: () = {
         // Late resources
         TX: Tx<USART2>,
         RX: Rx<USART2>,
+        received: u8,
+        errors: u8,
+        changed: bool,
     }
 
     // init runs in an interrupt free section
@@ -57,16 +60,40 @@ const APP: () = {
 
         // Separate out the sender and receiver of the serial port
         let (tx, rx) = serial.split();
-
+        let received = 0;
+        let errors = 0;
+        let changed = false;
         // Late resources
-        init::LateResources { TX: tx, RX: rx }
+        init::LateResources { 
+            TX: tx, 
+            RX: rx,
+            received: received,
+            errors: errors,
+            changed: changed,
+        }
     }
 
     // idle may be interrupted by other interrupts/tasks in the system
-    #[idle()]
-    fn idle(_cx: idle::Context) -> ! {
+    #[idle(resources = [received, errors, changed])]
+    fn idle(mut _cx: idle::Context) -> ! {
         loop {
-            continue;
+            let mut changed = false;
+            _cx.resources.changed.lock(|mut _changed| {
+                changed = *_changed;
+            });
+
+            if changed{
+                _cx.resources.received.lock(|received| {
+                    rprintln!("Received {}", *received);
+                });
+                _cx.resources.errors.lock(|errors| {
+                    rprintln!("Errors {}", *errors);
+                });
+
+                _cx.resources.changed.lock(|changed| {
+                    *changed = false;
+                });
+            }
         }
     }
 
@@ -78,12 +105,20 @@ const APP: () = {
         rprintln!("data {}", data);
     }
 
+
     // Task bound to the USART2 interrupt.
-    #[task(binds = USART2,  priority = 2, resources = [RX], spawn = [rx])]
+    #[task(binds = USART2,  priority = 2, resources = [RX, received, errors, changed], spawn = [rx])]
     fn usart2(cx: usart2::Context) {
         let rx = cx.resources.RX;
-        let data = rx.read().unwrap();
-        cx.spawn.rx(data).unwrap();
+        let data = rx.read();
+        if data.is_err(){
+            *(cx.resources.errors) += 1;
+        }
+        else{
+            *(cx.resources.received) += 1;
+            cx.spawn.rx(data.unwrap()).unwrap();
+        }
+        *(cx.resources.changed) = true;
     }
 
     extern "C" {
-- 
GitLab