{"id":12575,"date":"2023-05-07T09:11:50","date_gmt":"2023-05-07T09:11:50","guid":{"rendered":"https:\/\/www.qec.tw\/?p=12575"},"modified":"2025-11-11T13:33:01","modified_gmt":"2025-11-11T13:33:01","slug":"scoop-library","status":"publish","type":"post","link":"https:\/\/www.qec.tw\/zh\/86duino-library\/scoop-library\/","title":{"rendered":"SCoop Library"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">The SCoop Library is available from 86Duino Coding 500. It provides the API of the Simple Cooperative Scheduler for Arduino to access a light and simple environment for creating powerful multi-threaded programs or easy multi-tasking solutions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">There are lots of other alternatives from the best RTOS to the simplest \u201ctimer\u201d or interrupt libraries around the World Wide Web. This one fits in between and looks easy to use and powerful enough for most of us. It is mainly inspired by the Java Thread library and uses a traditional switching context mechanism taken from other RTOS like ChibiOS or freeRTOS.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Let\u2019s use it<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Here is an example of how to use the SCoop library with a very basic sketch:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>#include &quot;SCoop.h&quot; \/\/ create an instance of the scheduler called mySCoop \n\ndefineTask(Task1) \/\/ user definition of task1 object \nvolatile long count; \/\/ force any read\/write to memory\n\nvoid Task1::setup() {\n\tcount=0;\n};\n\nvoid Task1::loop() {\n\tsleepSync(1000);\n\tcount++;\n}; \n\ndefineTaskLoop(Task2) { \/\/ user quick definition of task2 object\n\tdigitalWrite(13, HIGH);\n\tsleep(100);\n\tdigitalWrite(13,LOW);\n\tsleep(100);\n}\n\nvoid setup() { \n\tSerial.begin(115200);\n\tmySCoop.start();\n} \nvoid loop() { \n\tlong oldcount=-1; yield(); \n\tif (oldcount!=count) {\n\t\tSerial.print(&quot;seconds spent :&quot;);\n\t\tSerial.println(count);\n\t\toldcount=count;\n\t}\n} <\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">In the main sketch setup(), the instruction <strong>mySCoop.start<\/strong>() prepare the scheduler and launch each individual setup() method for Task2 and then for Task1 (reverse order compared to declaration).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In the main loop(), the code is printing any changes to the \u201ccount\u201d variable.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can create as many task objects as you need as long as the microprocessor will have enough resources to hold them in memory and execute them in an acceptable time for you.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Each Task has its own \u201cstack\u201d context in order to hold local variables and to call other functions while remembering return address. By default, the defineTask macro is creating an array of 150 bytes for each AVR task or 256 bytes for each ARM task, but this can be overridden by adding your own value as a second parameter to the defineTask macro. Example: defineTask(Task2,200) will provide the task with 200 bytes of dedicated local stack.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is also possible to create a task without using the <strong>defineTask <\/strong>macro by just creating an instance of the <strong>SCoopTask <\/strong>object and calling a method later in the program to initialize your code and stack.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>SCoopTask myTask; \u2026 myTask.init(\u2026)<\/code><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How tasks work in a sketch :<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The Cooperative scheduler library is responsible for tasks and events management and is organized around a very simple function called <strong>yield()<\/strong>.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">This <em>yield <\/em>keyword (which sounds a bit weird for non-native English speakers) is part of the Arduino due Scheduler library. It has been recently introduced in the standard Arduino libraries as of build &gt;1.5. It is also part of the pjrc teensy core. Some function like delay() are using it, and the principal loop() function in the Teensy core is now including a default call to yield() at the end of user code. yield is also used in Java programming and declared in the Java Thread library.<\/p>\n<\/blockquote>\n\n\n\n<p class=\"wp-block-paragraph\">Basically, when your program is in a section of code where you have spare time, just call <strong>yield<\/strong>() and this will eventually go to the scheduler and switch to the next task registered in your sketch.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The scheduler will come back to the original code as soon as the other tasks also call the <strong>yield<\/strong>() function. Otherwise, the process is stuck in a task and the scheduler cannot take control back again! This is why the word Cooperative is important here, compared to other preemptive RTOS.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The big advantage of Cooperative multi-tasking is that all the existing libraries will be working well in a multi-tasking environment as they will not be interrupted by a preemptive mechanism, as most of the library does not accept reentrant calls (calling a function again before it is completed).<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Task Objects in more detail:<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Defining a task and providing a stack:<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The main idea of this library which is illustrated in the example is to consider a task as an object having its own stack and methods like <strong>setup() <\/strong>and <strong>loop()<\/strong>, which are inherited from the <strong>SCoopTask <\/strong>framework.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To create a task, just use the <strong>defineTask <\/strong>or <strong>defineTaskRun <\/strong>macro which will generate the header code for your object.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By default, a stack (an array of bytes) will be created for this object with the number of bytes declared in the second parameter. If you omit the stack-size parameter, then the array is set to a default value (150 for AVR, 256 for ARM), which is very comfortable for doing some basic computing on couple of local variables and also to call some Serial.print functions for example.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">If your code needs more local variables, or if it is calling a function that needs more space, then you have to anticipate this by allocating more stack-size in the declaration. Unfortunately, there is no easy way to calculate the maximum stack size needed, but the library contains a method called <strong>stackLeft() <\/strong>which will return the amount of memory in the stack that has not yet been used at this moment.<\/p>\n<\/blockquote>\n\n\n\n<p class=\"wp-block-paragraph\">Once the task is declared, an object is created and the Arduino environment will automatically call the object \u201cconstructor\u201d at the beginning of the program before entering in the main setup() or loop(). Therefore the object is automatically registered in a list of items that the scheduler will use later to start and launch each task (or events or timers) one by one.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can declare a task yourself by instantiating the basic object <strong>SCoopTask <\/strong>and then calling the init(\u2026) method with 3 parameters: address of the stack, size of the stack, and address of the function to be called instead of the loop() method, as in the below example. In that case, the <strong>defineStack <\/strong>macro can be used to facilitate the declaration of the stack array with some 8 bytes alignment needed for ARM platform:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>SCoopTask myTask; \ndefineStack(mystack,128) \nvoid mycode() { count+++; } \nvoid setup() { myTask.init(&amp;myStack,sizeof(mystack),&amp;mycode); \u2026 } <\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">The call to the init() method can also be grouped with the object declaration like this:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>defineStack(mystack,128) \nVoid mycode() { count+++; } \nSCoopTask myTask(&amp;myStack,sizeof(mystack),&amp;mycode); \/\/ implicit call to init() \nVoid setup() { \u2026 }  <\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\">Starting a task:<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Each task defined with the <strong>defineTask <\/strong>macro is expected to have its own <strong>setup<\/strong>() method. The scheduler will launch all the setup() of all tasks registered in the list with the command <strong>mySCoop.start<\/strong>(). The latest task registered will be launched first (reverse order compared to declaration in your sketch).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This command should be placed inside the main setup(). It will also initializes the Scheduler and reset the variables used for counting time. After this, each task is considered \u201cRUNNABLE\u201d for safely entering in their specific <strong>loop<\/strong>() method.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Running and leaving the task with yield()<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Each task defined with the <strong>defineTask <\/strong>or <strong>defineTaskLoop <\/strong>macro is also expected to have its own <strong>loop<\/strong>() method. The scheduler will launch this method periodically as part of a whole scheduling process. The task code inside this loop() can be blocking forever if needed, as long as the yield() (or sleep) method is called somewhere, sometime.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The mechanism to enter in and to switch out from a task is organized by the scheduler with its <strong>yield<\/strong>() function. Calling the method yield() from a task will most likely switch to the next task in the list and return to the Scheduler when reaching the last one. Then the Scheduler will launch all pending timers or event (see later in documentation) and will restart launching the tasks one by one.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Once all the other potential tasks (and timers or events) have been executed, it will give the control back to the original task as if it was a simple return from the call to the yield() method. The execution just continues afterward.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is recommended to systematically call yield() from the main Arduino sketch loop() by using <strong>mySCoop.yield<\/strong>(). This will force the loop to first launch all tasks and pending event\/timer before executing its own loop() code. It is possible to change this behavior by setting a predefine variable called SCoopYIELDCYCLE to 0 at the beginning of the SCoop.h file, so that the Scheduler is always in control of the switching mechanisms. With this approach, the main loop() would be considered as a tower of control for all other piece of code and therefore the code inside the main loop() would have a better priority of execution as it would be executed between each task switching or event\/timer launch.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\"><em>Remark:<\/em><br>The SCoop library forces a call to yield() at the end of the user\u2019s task loop(). If you implement your own looping mechanisms (e.g. while(1) { .. } inside the task loop()) then the program has to call the yield() method (or sleep) time to time somewhere in the loop.<\/p>\n<\/blockquote>\n\n\n\n<p class=\"wp-block-paragraph\">The SCoop library overrides the original Arduino yield() weak function with the one declared by the scheduler library called mySCoop.yield(). So you can also use the simple word yield() everywhere in your program or included files. This also provides a mechanism to hook the standard Arduino delay() function, which is now calling the yield() function (only as of Arduino library &gt;1.5), ensuring that the scheduler will always be under the control of the whole program.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Ending a task?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Not really, as the library allocates an amount of static memory for the stack, a task is not supposed to end once started! So it is up to the user to have code for stopping or starting, or waiting for events within the task loop(), eventually by using pause() and resume(). <em>(see \u201cAndroid scheduler\u201d for dynamic tasks)<\/em><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Method available in your task object:<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Within the code of a task object, it is possible to call several methods inherited from the <strong>SCoopTask <\/strong>base object:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>sleep(time)<\/code>: same behavior as the standard delay() function, but the spare time is used to give the control back to the scheduler immediately or to execute the other pending tasks.<\/li>\n\n\n\n<li><code>sleepSync(time)<\/code>: same function as sleep, but the time to sleep is synchronized with the previous call to a sleep() or sleepSync() function, enabling a strict periodic time handling (\u201cno jitter\u201d).<\/li>\n\n\n\n<li><code>sleepUntil(Boolean)<\/code>: just wait for the Boolean variable to become true (and then set it to false) and give the control back to the scheduler in the meantime. It is mandatory to use the volatile variable for this flag, as the status change will come from another task or from the main loop() program itself.<\/li>\n\n\n\n<li><code>sleepUntil(Boolean,timeOut)<\/code>: (as of V1.2) same as sleepUntil, but will return anyway after the given timeOut period. It can be used as a function in an expression and return false in case of timeout.<\/li>\n\n\n\n<li><code>stackLeft()<\/code>: return a number of bytes never used in the task stack since the task was started.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">This function can also be called from the main loop() in the Arduino sketch, outside of the task object context, by referencing it with the task object itself or with a global pointer:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>void printstack(){\n  SCoopEvent* ptr=SCoopFirstTask; \/\/ global library type and variable \n  while (ptr) { \n    Serial.println(reinterpret_cast&lt;SCoopTask*&gt;(ptr)-&gt;stackLeft()); \n    ptr=ptr-&gt;pNext;\n  } \n}\n\nVoid loop() { \n  printstack(); \u2026 or \u2026 Serial.println(Task1.stackLeft());\n} <\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\">Cross-task talking and Volatile<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Nothing to do with chickens here. Due to compiler optimization, very often a variable is made local or uses a temporary register. In order to pass information across tasks or to use a variable in a multiple-thread program (e.g., one task is writing, and the other one is reading), we have to declare the common variable as <strong>volatile<\/strong>, which forces the compiler to read and write them into memory at each access.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To simplify variable declaration, the SCoop library predefines some types for int8,16,32 and uint8,16,32, and Boolean, preceding the original Arduino type name with a \u201cv\u201d and removing the \u201c_t\u201d like:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>vui16 mycount; \/\/ exact same as volatile uint16_t mycount \nvbool OneSecond = false; \/\/ exact same as volatile Boolean OneSecond <\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\">Timers<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The library provides a complementary <strong>SCoopTimer <\/strong>object which can be used to create periodic actions which will be orchestrated by the Scheduler. You can instantiate as many timers as you need, and they can even be declared temporarily as a local object in a function or task. A timer doesn\u2019t need a stack context as you enter; you leave from a timer in a single atomic yield() operation; they use the normal stack of the main Arduino sketch. Timers have to be fast as they cannot give control back to the scheduler in any case (the local yield() method is disabled). Timer looks like an MCU timer interrupts but with the possibility to call any of your existing functions or libraries from them without the risk of a system crash\u2026<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Defining a Timer:<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The specific macro <strong>defineTimerRun <\/strong>can be used to declare your own timer object with 1 or 2 parameters. The first parameter is the name of your object; the second option is the period of the timer:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>defineTimerRun(myTimer,1000){ ticSecond=true; countSecond++ } <\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">The code of this timer is implicitly attached to myTimer::run() method. It must be fast and non-blocking. The timer are registered in the same list as the tasks and, therefore, will be triggered by the scheduler during a call to yield(). Once the time elapsed since the last call has reached the defined period, the run() method is executed once.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If a timer needs time to complete (say some milli-seconds), it is suggested to use a Task instead, with the sleepSync() function at the very beginning of the loop() method and some calls to yield() or yield(0) in the blocking or slow section. This code will give the exact same behavior as a timer(1000) definition:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>defineTaskLoop(myTimer,100) { sleepSync(1000); ticSecond=true; countSecond++ }<\/pre><\/div>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\"><em>Remark: In this example, we reduce the default stack size by forcing the value 100 with the second parameter, because the task loop() doesn\u2019t need that much as it doesn\u2019t call any other function and has no local variables. This is to be experimented case by case.<\/em><\/p>\n<\/blockquote>\n\n\n\n<h3 class=\"wp-block-heading\">Starting and monitoring timer:<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A call to <strong>mySCoop.start<\/strong>() will initialize all the timers registered and will enable them if the time period was provided as the second parameter of the <strong>defineTimerRun <\/strong>macro. If not, then this is up to the program to initialize this later with a call to the method <strong>schedule<\/strong>(time) (see below).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The following methods provide other means to modify or monitor the timers:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>schedule(time)<\/code>: enable the timer and prepare it to be launched every \u201ctime\u201d ms.<\/li>\n\n\n\n<li><code>schedule(time, count)<\/code>: same as schedule(time), adding a maximum number of execution.<\/li>\n\n\n\n<li><code>getPeriod()<\/code>: return the value registered for the time period of this timer.<\/li>\n\n\n\n<li><code>setPeriod()<\/code>: force a value for the time period.<\/li>\n\n\n\n<li><code>getTimeToRun()<\/code>: return the time in ms before the next execution of the timer run() method.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Another way of declaring timer with predefined macros:<br><strong>defineTimer(<\/strong>T1, optional period) gives the possibility to declare both a T1::setup() and a T1::run() method for this object, and this is useful if we want to add some setup code inside this object instead of writing them in the main setup(): this is not backward compatible with V1.1 as the setup() is now mandatory! please rework your program to use defineTimerRun() instead if you do not need setup().<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>defineTaskLoop(myTimer,100) { sleepSync(1000); ticSecond=true; countSecond++ }<\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">By extension 2 other macros can be used for defining timer class:<br><strong>defineTimerBegin<\/strong>(event[,period]) and <strong>defineTimerEnd<\/strong>(event). See example 2 in the library as a showcase.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Events<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The library provides a complementary object <strong>SCoopEvent <\/strong>which can be used to handle code to be executed by the scheduler upon an external event or trigger. As an example, it is possible to trigger an event from an interrupt (isr, signal), but the corresponding run() code will be executed only by the scheduler outside of the interrupt context. This enables to write of complex event handling and calling library functions without the criticality needed for coding hardware interrupts.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Like the <strong>SCoopTimer <\/strong>object, the <strong>SCoopEvent <\/strong>has no stack context and is expected to be as fast as possible in order to keep the scheduling fluent. If an event needs a lot of time to complete, then it should be declared as a permanent task, waiting for a volatile flag by using the <strong>sleepUntil<\/strong>() method.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Example of event declaration and usage:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>defineEventRun(myevent){ Serial.println(&quot;trigger received&quot;); } \nisr(pin) { myevent.set(); } \/\/ or myevent=true; <\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">The event object has only one public method to set the trigger flag:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>set()<\/code>: set the trigger flag to true. The event will be launched by the scheduler by calling yield().<\/li>\n\n\n\n<li><code>set(value)<\/code>: set the trigger value, if false, nothing happens. If true, then equivalent to set()<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The event trigger flag can also be set directly by an assignment like \u201cmyevent=true\u201d, as the library overloads the standard \u201c=\u201d operator for this object.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>defineEvent<\/strong>(event) can be used to define both event::setup() and event::run() , as for timers. This is not backward compatible with V1.1! please use defineEventRun(event) instead, if you do not need setup().<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By extension 2 other macros can be used for defining event classes:<br><strong>defineEventBegin<\/strong>(event) and <strong>defineEventEnd<\/strong>(event). See example 2 in the library as a showcase.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\"><strong>Fifo \/ first in first out new in V1.1<\/strong><\/p>\n<\/blockquote>\n\n\n\n<p class=\"wp-block-paragraph\">The SCoop library provides a complementary object <strong>SCoopFifo <\/strong>and a macro called <strong>defineFifo <\/strong>which will provide nice support to manage first-in, first-out buffers for bytes, integers, long, or any type of structure data below 256 bytes. This can be very useful to exchange data between tasks, events,s or timers and another task with a producer-consumer or sender-receiver model in a synchronous way (no synchronization needed between tasks).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here is an example of how to declare a fifo buffer of 100 integers and to use it between a timer doing analog sampling and a task using them for monitoring variation.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>defineFifo(analogBuf,int16_t,100) \n\nint16_t A,B; \n\ndefineTimer(anaRead,10) \/\/ read analog every 10ms \nvoid anaRead::run() {\n  A=analogRead(1); analogBuf.put(&amp;A);\n} \n\ndefineTaskLoop(task1) { \n  while(analogBuf&lt;32) yield(0); \/\/ wait for 32 items in the buffer \n  \n  int16_t avg=0; \n  for (int i=0; i&lt;32; i++) {\n    analogBuf.get(&amp;B);\n    avg += B;\n  } \n  avg \/= 32; yield(); \n  Serial.print(&quot;average analog value for 32 samples = &quot;);Serial.println(avg); \n} <\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">The <strong>SCoopFifo <\/strong>also provides the following methods:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>put(&amp; var)<\/code>: add the value of the variable to the buffer. Return true if the result is successful or false if the buffer was already full.<\/li>\n\n\n\n<li><code>putChar(val)<\/code> \/ <code>putInt(val)<\/code> \/ <code>putLong(val)<\/code>: can be used to directly add a given value into the buffer without needing an intermediate variable.<\/li>\n\n\n\n<li><code>get(&amp; var)<\/code>: take the older value from the buffer and store it in the variable passed. Return true if successful or false if the buffer was empty.<\/li>\n\n\n\n<li><code>flush()<\/code>: empty the buffer and return the size of the buffer (number of items) as per declaration.<\/li>\n\n\n\n<li><code>flushNoAtomic()<\/code>: same as flush, but doesn\u2019t touch interrupts. Should not be used in conjunction with ISR.<\/li>\n\n\n\n<li><code>count()<\/code>: return the amount of samples available in the buffer.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">It is also possible to use the name of the object inside an integer expression which will return the same value as the method <code>count()<\/code>.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\"><strong>Virtual timer\/delay: SCoopDelay <\/strong>and <strong>SCoopDelayus new in V1.2<\/strong><\/p>\n<\/blockquote>\n\n\n\n<p class=\"wp-block-paragraph\">The SCoop library now uses and provides a simple object to facilitate delays or timeout measurements with a class named <strong>SCoopDelay<\/strong>. This looks a bit like <strong>TimerDown <\/strong>(see later in the document).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The object can be declared with or without an auto-reload value. If not used, the reload storage variable will be hopefully automatically removed by the linker. If used then the timer\/delay automatically starts.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Typical usage:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>SCoopDelay time; \ntime = 10; while (time) yield(); \/\/ this launch yield() during 10ms \nSCoopDelay t10seconds(10000); \nIf (T10seconds.reloaded()) { \/* do something every 10 seconds *\/ } <\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">Methods for SCoopDelay objects:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>set(time)<\/code>: define the starting time for the delay. The delay will then start counting down to 0;<\/li>\n\n\n\n<li><code>get()<\/code>: return the value of the delay. if delay is elapsed, the result is 0.<\/li>\n\n\n\n<li><code>add(time)<\/code>: add a certain amount of time to the delay.<\/li>\n\n\n\n<li><code>sub(time)<\/code>: subtract a certain amount of time to the delay.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">These 4 methods can also be transparently used by directly using the SCoopDelay object in an expression like x=delay or delay=x or delay+=x or delay-= x. thanks to operator overloading.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>elapsed()<\/code>: return true if the delay is elapsed.<\/li>\n\n\n\n<li><code>reloaded()<\/code>: same as elapsed, but automatically restart the delay with the reload value if defined.<\/li>\n\n\n\n<li><code>setReload(time)<\/code>: predefine and attach a reload value to the object. Same as if provided during object declaration.<\/li>\n\n\n\n<li><code>getReload()<\/code>: return the value of the reload parameter attached to the object.<\/li>\n\n\n\n<li><code>reload()<\/code>: add the reload value to the SCoopDelay object.<\/li>\n\n\n\n<li><code>initReload()<\/code>: set the SCoopDelay object with its reload value.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">All the values are defined in int32 as defined by the <strong>SCDelay_t <\/strong>variable at the beginning of SCoop.h file.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By extension, a <strong>SCoopDelayus <\/strong>object is also provided by the library, which is the same but using parameters in microseconds. The values are int16 for AVR or int32 for ARM, as defined by the micros_t variable at the beginning of the SCoop.h file.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Time Counters:<\/strong><br>The SCoop library provides 2 powerful objects, totally independent of the scheduler, to handle time counting up and down. The time base for a tic count can be specified from 1 ms up to 30 seconds (int16). There are no limitations on the number of timers that can be declared.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>TimerUp<\/strong>: will provide an object counting time from 0 to a maximum amount to be defined in the object declaration (can be 0). Once the maximum is reached, the counters go back to 0, and it is possible to monitor the rollover event with the <strong>rollOver<\/strong>() method in order to start an action. Example:<\/li>\n<\/ul>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>#include &lt;TimerUp.h&gt; \nTimerUp counterMs(0); \/\/ do nothing, need further initialization \nTimerUp myMillis(1000); \/\/ will count up from 0 to 999 every 1ms \nTimerUp mySeconds(3600,1000); \/\/ will count from 0 to 3599 every 1000ms \n\u2026 \nvoid loop() { \n  if (myMillis.rollOver()) {\n  \tSerial.print(&quot;one more second elapsed&quot;)\n  }\n    \n  if (mySeconds.rollOver()) {\n  \tSerial.print(&quot;one more hour elapsed&quot;)\n  }\n} <\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">The object can also be used directly in an expression or assignment.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>TimerUp myTime(1000); \n\u2026 \nvoid loop() { \nif (skip) &amp;&amp; (myTime &gt; 500) { mytime = 800; } \/\/ will read and force timer <\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">The value set during the declaration for the rollover can be modified later on with the method <strong>setRollOver<\/strong>(timeMax).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>TimerDown <\/strong>provides another type of powerful object counting down from a maximum value to 0. Once the down counting reaches 0, the counter definitely keeps the value 0 until the program force it to another value. For example:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>#include &lt;TimerUp.h&gt; \n#include &lt;TimerDown.h&gt; \nTimerUp tic(100,10) \/\/ count up from 0 to 99 every 10ms \nTimerDown msLeft(0); \/\/ will count down every ms \nTimerDown secondsLeft(3600,1000); \/\/ count from 3599 to 0 every 1000ms \n\u2026 \nvoid loop() { \n  while (secondsLefts) { \n    if (tic.rollOver()){\n    \tmsLeft=1000; \/\/ restart this counter \n        Serial.print(secondsLeft);\n        Serial.print(&quot; seconds and &quot;); \n        Serial.print(msLeft);\n        Serial.println(&quot;ms before end&quot;);\n      }\n  }\n} <\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">In addition, the method below can be used for TimerUp and TimerDown objects:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>Init(time, timeBase)<\/code>: initializes the counter with a given timemax and a given time base. As an example counter.init(5,1000) will initialize the counter (up or down) with the value corresponding to 5 seconds. if it is a TimerUp then it will count from 0 to 4. If it is a TimerDown, it will count from 5 to 0.<\/li>\n\n\n\n<li><code>set(time)<\/code>: forces a new value in the counter. This is equal to assigning a value like counter=100;<\/li>\n\n\n\n<li><code>reset()<\/code>: just forces the counter to 0. Also, clear the rollover flag for TimerUp objects.<\/li>\n\n\n\n<li><code>get()<\/code>: return the value of the timer. A timer can also be read directly within an integer expression like x=counterMs;<\/li>\n\n\n\n<li><code>pause(time)<\/code>: the timer will keep its actual value until it is resumed.<\/li>\n\n\n\n<li><code>resume()<\/code>: if the timer was paused, then it is resumed and starts counting again from this value.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Library compilation option:<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">It is possible to edit the files named <strong>TimerUp.h <\/strong>and T<strong>imerDown.h <\/strong>and to change some values in the first lines inside the #define statement, which will impact the compilation pre-processing<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">As an example, time-based handling can be disabled in order to make the library more compact. Then the default time base is the millisecond. It is also possible to change the name of the original object class TimerUp (or TimerDown) by your own object name like for example TimeCounter, if preferred.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is finally possible to force the method parameter as \u201cint\u201d instead of \u201clong\u201d, but the internal timing computation remains in 32bits mode. (remark: for ARM, int is still 32bits!)<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">More technical things<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This picture represents the objects classes an some instances and how this works together with the standard setup() and loop() function in the Arduino sketch. This aims to illustrate the explanation given in previous chapters:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img fetchpriority=\"high\" decoding=\"async\" width=\"865\" height=\"649\" src=\"https:\/\/www.qec.tw\/wp-content\/uploads\/2023\/06\/image.png\" alt=\"scoopTechnicalThings\" class=\"wp-image-12749\" srcset=\"https:\/\/www.qec.tw\/wp-content\/uploads\/2023\/06\/image.png 865w, https:\/\/www.qec.tw\/wp-content\/uploads\/2023\/06\/image-300x225.png 300w, https:\/\/www.qec.tw\/wp-content\/uploads\/2023\/06\/image-768x576.png 768w, https:\/\/www.qec.tw\/wp-content\/uploads\/2023\/06\/image-16x12.png 16w, https:\/\/www.qec.tw\/wp-content\/uploads\/2023\/06\/image-600x450.png 600w\" sizes=\"(max-width: 865px) 100vw, 865px\" \/><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Simple Cooperative Scheduler for Arduino\u00ae ARM &amp; AVR Aka \u00ab SCoop \u00bb, more details or resources see <a href=\"https:\/\/code.google.com\/p\/arduino-scoop-cooperative-scheduler-arm-avr\/\" target=\"_blank\" rel=\"noopener\">here<\/a>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\"><a href=\"https:\/\/www.qec.tw\/86duino\/libraries\/\">Libraries Reference Home<\/a><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><em>The text of the 86Duino reference is a modification of&nbsp;<a href=\"http:\/\/arduino.cc\/en\/Reference\/HomePage\" target=\"_blank\" rel=\"noopener\">the Arduino reference<\/a>&nbsp;and is licensed under a&nbsp;<a href=\"http:\/\/creativecommons.org\/licenses\/by-sa\/3.0\/\" target=\"_blank\" rel=\"noopener\">Creative Commons Attribution-ShareAlike 3.0 License<\/a>. Code samples in the reference are released into the public domain.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The SCoop Library is available from 86Duino Coding 500. It provides the API of the Simple Cooperative Scheduler for Arduino to access a light and [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":12576,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[198,268],"tags":[162,314],"class_list":["post-12575","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-86duino-library","category-scoop","tag-86duino","tag-lib"],"_links":{"self":[{"href":"https:\/\/www.qec.tw\/zh\/wp-json\/wp\/v2\/posts\/12575","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.qec.tw\/zh\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.qec.tw\/zh\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.qec.tw\/zh\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.qec.tw\/zh\/wp-json\/wp\/v2\/comments?post=12575"}],"version-history":[{"count":1,"href":"https:\/\/www.qec.tw\/zh\/wp-json\/wp\/v2\/posts\/12575\/revisions"}],"predecessor-version":[{"id":16974,"href":"https:\/\/www.qec.tw\/zh\/wp-json\/wp\/v2\/posts\/12575\/revisions\/16974"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.qec.tw\/zh\/wp-json\/wp\/v2\/media\/12576"}],"wp:attachment":[{"href":"https:\/\/www.qec.tw\/zh\/wp-json\/wp\/v2\/media?parent=12575"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.qec.tw\/zh\/wp-json\/wp\/v2\/categories?post=12575"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.qec.tw\/zh\/wp-json\/wp\/v2\/tags?post=12575"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}