a simple c coroutine for mbed paltform

Dependencies:   mbed

Files at this revision

API Documentation at this revision

Comitter:
mintisan
Date:
Sun Mar 06 07:22:27 2016 +0000
Commit message:
initial c coroutine for mbed

Changed in this revision

coroutine.h Show annotated file Show diff for this revision Revisions of this file
main.cpp Show annotated file Show diff for this revision Revisions of this file
mbed.bld Show annotated file Show diff for this revision Revisions of this file
diff -r 000000000000 -r 0177715f0996 coroutine.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/coroutine.h	Sun Mar 06 07:22:27 2016 +0000
@@ -0,0 +1,34 @@
+#ifndef COROUTINE_H_
+#define COROUTINE_H_
+
+#ifdef __cplushplus
+extern "C"{
+#endif
+
+/**
+ * C coroutine 
+ * https://github.com/mintisan/mintisan.github.io/wiki/C#coroutine
+ */
+
+#define cr_start()              \
+        static int __s = 0;     \
+        switch(__s){            \
+            case 0:
+
+// '\' doesn't count for one line in C
+#define cr_yield(condition) do{      \
+            __s = __LINE__ ;     \
+                case __LINE__:      \
+                    if(condition)   \
+                    return;         \
+                }while(0)
+
+#define cr_end()                \
+        } __s = 0;            
+
+
+#ifdef __cplushplus
+}
+#endif
+
+#endif
diff -r 000000000000 -r 0177715f0996 main.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Sun Mar 06 07:22:27 2016 +0000
@@ -0,0 +1,55 @@
+#include "mbed.h"
+#include "coroutine.h"
+
+volatile uint16_t cr_time1;
+volatile uint16_t cr_time2;
+
+void user_thread1(void);
+void user_thread2(void);
+
+Ticker toggle_led_ticker;
+DigitalOut led1(LED1);
+DigitalOut led2(LED2);
+
+void isr_ticker() {
+    cr_time1++;
+    cr_time2++;
+}
+
+
+
+int main(void) {
+    // Init the ticker with the address of the function (isr_ticker) to be attached and the interval (1 ms)
+    toggle_led_ticker.attach(&isr_ticker, 0.001);
+    while (true) {
+        // Do other things...
+        user_thread1();
+        user_thread2();
+    }
+}
+
+void user_thread1(void)
+{
+    cr_start();
+    
+    // inital once each loop
+    cr_time1 = 0;
+    // waiting for condition is satisfied, or will be yield
+    cr_yield(cr_time1 != 1000);
+    led1 = !led1;
+            
+    cr_end();
+}
+
+void user_thread2(void)
+{
+    cr_start();
+    
+    // inital once each loop
+    cr_time2 = 0;
+    // waiting for condition is satisfied, or will be yield
+    cr_yield(cr_time2 != 800);
+    led2 = !led2;
+
+    cr_end();           
+}
diff -r 000000000000 -r 0177715f0996 mbed.bld
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed.bld	Sun Mar 06 07:22:27 2016 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/mbed_official/code/mbed/builds/87f2f5183dfb
\ No newline at end of file