isr example

Files at this revision

API Documentation at this revision

Comitter:
bridadan
Date:
Mon Oct 15 17:26:47 2018 -0500
Parent:
6:878a39536de3
Commit message:
Updating example to show usage of the idle thread. Also showing Thread and Handler modes.

Changed in this revision

main.cpp Show annotated file Show diff for this revision Revisions of this file
diff -r 878a39536de3 -r 985db97e8ae0 main.cpp
--- a/main.cpp	Mon Oct 15 17:25:24 2018 -0500
+++ b/main.cpp	Mon Oct 15 17:26:47 2018 -0500
@@ -1,32 +1,73 @@
 #include "mbed.h"
 
+Ticker ticker;
 Thread thread;
-Ticker ticker;
-Queue<uint32_t, 5> queue;
-DigitalOut myled(LED1);
+Queue<const char*, 5> trail;
+
+// Since we're printing from multiple threads, we need a mutex
+Mutex print_lock;
+
+enum ExecutionTypes {
+    IDLE,
+    USER,
+    ISR
+};
 
-void queue_isr() {
-    queue.put((uint32_t*)2);
-    myled = !myled;
-}
+const char* ExecutionMessages[] = {
+    "the idle thread",
+    "a user thread",
+    "interrupt context"
+};
 
-void queue_thread() {
-    while (true) {
-        queue.put((uint32_t*)1);
-        wait(1);
+void handler() {
+    // Check to see if we're in interrupt context
+    if (core_util_is_isr_active()) {
+        // Do not print since we're in interrupt context
+        trail.put(&(ExecutionMessages[ISR]));
+    } else {
+        // Safe to print since we're in a user thread
+        print_lock.lock();
+        printf("Starting user thread\r\n");
+        print_lock.unlock();
+        while(true) {
+            trail.put(&(ExecutionMessages[USER]));
+            wait(5);
+        }
     }
 }
 
-int main (void) {
-    thread.start(callback(queue_thread));
-    ticker.attach(queue_isr, 1.0);
+void custom_idle_function() {
+    // Custom idle behavior would go here
+    // We won't print here since the default idle thread's stack is too small
+    trail.put(&(ExecutionMessages[IDLE]));
+
+    // Switch back to the default idle behavior
+    Kernel::attach_idle_hook(NULL);
+}
 
+int main() {
+    printf("Starting execution example\r\n");
+
+    // Attach the custom idle thread function
+    Kernel::attach_idle_hook(custom_idle_function);
+
+    // Trigger the interrupt every 3 seconds
+    ticker.attach(handler, 3);
+
+    // Start the user thread
+    thread.start(handler);
+
+    // Get the past exectuion trail
     while (true) {
-        osEvent evt = queue.get();
+        osEvent evt = trail.get();
         if (evt.status != osEventMessage) {
-            printf("queue->get() returned %02x status\n\r", evt.status);
+            print_lock.lock();
+            printf("Failed to retrieve the execution trail (returned %02x)\r\n", evt.status);
+            print_lock.unlock();
         } else {
-            printf("queue->get() returned %d\n\r", evt.value.v);
+            print_lock.lock();
+            printf("Execution was in %s\r\n", *(const char**)evt.value.v);
+            print_lock.unlock();
         }
     }
 }