![](/media/cache/profiles/c5c2f3677cc6e565cbf176c7f8982c80.jpg.50x50_q85.jpg)
a simple c coroutine for mbed paltform
Revision 0:0177715f0996, committed 2016-03-06
- Comitter:
- mintisan
- Date:
- Sun Mar 06 07:22:27 2016 +0000
- Commit message:
- initial c coroutine for mbed
Changed in this revision
--- /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
--- /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(); +}
--- /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