Lecture 34 Protothreads Today we try to raise the abstraction level of writing microcontroller software. Our key objective is to make programs easier to understand and to write, especially those that involve time. We first recap the key ideas about software methodology in the course. Then we extend this with a concept called TIMED cyclic executive. Then we show that such programs become easier to write in a THREADED approach, and we discuss one example of a threaded approach called ProtoThreads. 10:12 Key ideas of software structure in this course (1) KEY IDEA 1: SOFTWARE IS LOGIC GLUE FOR HARDWARE PERIPHERALS The role of software is the ultimately provide logical integration of hardware peripherals. The hardware peripherals generate events and data which are processed by the software, who in turn drives the hardware peripherals. The classic example is that of the LED driven by the pushbutton: while (1) if (pushbutton_pressed()) led_on(); else led_off(); Note that the while loop around the if statement is essential. We want to build a 'logic wire' that connects the button to the LED. As soon as the button is pressed, the logic wire needs to relay that signal to the LED. (2) KEY IDEA 2: A CYCLIC EXECUTIVE IS A SYSTEMATIC WAY OF WRITING SOFTWARE GLUE So conceptually, the software is written as: while (1) if (input) do_action() The generic term for this writing style is the CYCLIC EXECUTIVE. When we have multiple inputs, we would enumerate them one after the other in a while loop: while (1) { if (i1 = hw_input1()) { v1 = process1(i1); output_action1(v1); } if (i2 = hw_input2()) { v2 = process1(i2); output_action1(v2); } } We know that, if we scan the inputs quickly enough, we will never miss an input event. However, keep in mind that the software can only be in one place at a time. Logically, we think of this program as two parallel logic wires, but the implementation forces us to implement them in a sequential manner. Because the speed of the CPU we get the illusion of concurrency. (3) KEY IDEA 3: INTERRUPTS ARE EVENTS FROM HARDWARE So far, we looked upon hardware inputs as passive, and they are scanned by active software. i1 = hw_input1() Interrupts change that notion. They allow the hardware to place a value into i1 when the hardware chooses so. The hardware will need to interrupt the software and temporarily take control of the processor inside of an ISR. That is, the ISR writes a shared variable, marks it as written, and then it is picked up by the cyclic executive volatile unsigned value, value_written; my_isr() { value = input value_written = 1; clear_int_flag(); } while (1) { if (value_written) { v1 = process1(value); value_written = 0; output_action1(v1); } if (i2 = hw_input2()) { v2 = process1(i2); output_action1(v2); } } We have also used interrupts to mark events, which are specific points in time. A timer expires, the AD conversion has finished, the ACL detects activity, etc, are all events. (4) KEY IDEA 4: TO WORK WITH A SEQUENCE OF ACTIVITIES INSTEAD OF A SINGLE ONE, USE AN FSM The cyclic executive while loop has a single level of hierarchy. You always have to write it as: while (1) { if (input1) do_action1(); if (input2) do_action2(); ... } If you want a sequence of inputs (or events), this requires an FSM. Indeed, let's say you want do_action3() when a sequence input1 followed by input3 happens. An intuitive, but WRONG, way of writing this is: while (1) { if (input1) { do_action1(); while (!input3) ; do_action3(); } if (input2) do_action2(); ... } The problem with this code is that it 'blinds' the second if-statement while we wait inside of the first if statement. We have solved this problem with a FINITE STATE MACHINE: while (1) { switch (state1) { case s0: do_action1(); if (input1) state1 = s1; break; case s1: if (input3) do_action3(); state1 = s0; break; } if (input2) do_action2(); ... } What the FSM really buys is is the ability to recall previous inputs, and therefore we can adapt the output_action based on a sequence of input events instead of a single, immediate input. 10:20 Timed Execution We will now extend the concept of cyclic executive to include time. We call this the TIMED CYCLIC EXECUTIVE. Eventually, our objective is to write programs with precise time delays, such as: - blink the LED every 500ms - when this input is high, wait for exactly 250ms and read it again We could create a timer for each period task, but a better approach is to employ one single fine-granular timing generator and create derived flags from that. That is the basis for the timed cyclic executive. The fine-granular timer is a Timer ISR that expires every second: tSWTimer everysec; InitSWTimer (&everysec, TIMER32_1_BASE, 3000000); StartSWTimer(&everysec); The following program creates three different activities that each run at a different period. One LED blinks at 500ms, a second LED blinks at 300ms, a third LED blinks at 100ms int main(void) { InitTimer(); InitLEDs(); tSWTimer t500ms; tSWTimer t300ms; tSWTimer t100ms; InitSWTimer (&t500ms, TIMER32_1_BASE, 1500000); InitSWTimer (&t300ms, TIMER32_1_BASE, 1000000); InitSWTimer (&t100ms, TIMER32_1_BASE, 300000); StartSWTimer(&t500ms); StartSWTimer(&t300ms); StartSWTimer(&t100ms); while (1) { if (SWTimerExpired(&t500ms)) { Toggle_Booster_Red_LED(); } if (SWTimerExpired(&t300ms)) { Toggle_Launchpad_Right_Red_LED(); } if (SWTimerExpired(&t100ms)) { Toggle_Launchpad_Left_LED(); } } } 10:35 Software Delays To capture the statement 'after 250ms', we need to work with a software delay. We can extend the above software timer concept quite easily with an 'after' call: We do this with the 'after' and an 'expired' call: void after(tSWTimer *T, unsigned d) { InitSWTimer(T, TIMER32_1_BASE, d); StartSWTimer(T); } int expired(tSWTimer *t) { return SWTimerOneShotExpired(T); } When we call 'after', we set the software timer to expire d ticks after the current time. We then test 'expired()' to check when the timer is expired. Consider the following program, which is a mix of software delays and a sequence of activities: while (1) { toggle LED1; wait for 200ms; toggle LED2; wait for 800ms; toggle LED3; wait for 1600ms; } We can program this, combining the ideas above, using software delays and a finite state machine, and we obtain a timed cyclic executive as follows: int main(void) { unsigned nextled = 0; InitTimer(); InitLEDs(); tSWTimer tms; after(&tms, 300000); while (1) { if ((nextled == 0) && (expired(&tms))) { Toggle_Booster_Red_LED(); after(&tms, 600000); nextled = 1; } if ((nextled == 1) && (expired(&tms))) { Toggle_Launchpad_Right_Red_LED(); after(&tms, 2400000); nextled = 2; } if ((nextled == 2) && (expired(&tms))) { Toggle_Launchpad_Left_LED(); after(&tms, 4800000); nextled = 0; } } } Note that I've used a shorthand for the FSM using if-statements rather than a case statement. The variable nextled plays the role of current state. Nevertheless, we have to admit that the code becomes tedious to write, in particular because it was so easy to express what we wanted in the first place: while (1) { toggle LED1; wait for 200ms; toggle LED2; wait for 800ms; toggle LED3; wait for 1600ms; } Finite state machines are, in fact, not the most elegant way to express sequence. We will next introduce a new idea, one which is fundamentally different from the concept of cyclic executive, and which will be able to reflect the pseudo code above much easier. That new idea is THREADED EXECUTION. 10:40 Threaded Execution In the previous example, we need to remember 'where we are' in the execution. The if-statements look at what LED was turned on previously, and then decide what LED should be turned in next. Instead, we would like to have something that looks as close as possible to the following: while (1) { Toggle_Booster_Red_LED(); after(&t1, 600000); while (!expired(&t1)) ; Toggle_Launchpad_Right_Red_LED(); after(&t1, 2400000); while (!expired(&t1)) ; Toggle_Launchpad_Left_LED(); after(&t1, 4800000); while (!expired(&t1)) ; } Of course, if we would write this as shown, we would break the cyclic executive principle, because now we are busy-waiting inside of the main while loop. The reason of this difficulty is that we don't have the ability to remember our 'current position' in a logical sequence unless we're adding a state machine. The solution to this problem is to introduce a 'thread', a logical thread of control in your program. In a simple cyclic executive we have only one thread of control. while (1) { // .. the main thread } When we have multiple threads of control, the processor will be switched back and forth between each thread. while (1) { // .. thread 1 dosomethings1(); __contextswitch(); } while (1) { // .. thread 2 dosomethings2(); __contextswitch(); } Indeed, there are two while loops. The reason why we are able to run two while loops is that the processor can go back and forth between them. Each time a thread calls '__contextswitch()', the processor knows the thread wants to pause, and therefore jumps from one while loop to the other. There will be come C magic behind the scenes to make this happen, but for the time being we will only focus on how we can used threads, not on how they're technically implemented. In the example above, it would appear that each of the while loops make one iteration, alternately. We will illustrate a solution for the problem of turning LEDs on at different intervals as a threaded program. We will make use of a C library called 'protothreads'. Library is probably a bit too big a word; it's really only a few include files. We will build a system with two threads: 1. The first thread blinks the LED every 200ms We will be using the timekeeping functions created earlier (SWTimerExpired(..)) 1. The second thread blinks the launchpad LEDs alternately every 800ms. We will be using the timekeeping functions created earlier (SWTimerExpired(..)) Here is the main program: int main(void) { static struct pt pt1, pt2; InitTimer(); InitLEDs(); PT_INIT(&pt1); PT_INIT(&pt2); while (1) { protothread1(&pt1); protothread2(&pt2); } } This program creates two threads of control, pt1 and pt2. You can think of these as two concurrent cyclic executives (while loops). Each of them is coded in a different function. protothread1() contains the first while loop, protothread2() contains the second while loop. pt1 and pt2 are data structures used by the library to move from function protothread1() to function protothread2(). Here is one of the protothreads: static int protothread1(struct pt *pt) { static tSWTimer t200ms; PT_BEGIN(pt); InitSWTimer (&t200ms, TIMER32_1_BASE, 600000); while (1) { PT_WAIT_UNTIL(pt, SWTimerExpired(&t200ms)); Toggle_Booster_Red_LED(); } PT_END(pt); } There's only one piece of magic in this function, which is PT_WAIT_UNTIL(pt, SWTimerExpired(&t200ms)). What happens there is that the function periodExpired(&t2) is tested, and if it is true, then this thread will stop and switch to the other protothread. Hence, inside of PT_WAIT_UNTIL, there's something similar to '__context_switch()' mentioned above. The only time when periodExpired(&t2) will be true, is after 200ms (or each 200ms). In that case, the LED is toggled, and the PT_WAIT_UNTIL will block the thread until the next interval. The other thread is slightly more complex, because we want this thread to work in multiple steps. Hence, it will have multiple PT_WAIT_UNTIL functions: static int protothread2(struct pt *pt) { static tSWTimer t800ms; PT_BEGIN(pt); after(&t800ms, 2400000); while (1) { PT_WAIT_UNTIL(pt, SWTimerExpired(&t800ms)); TurnOFF_Launchpad_Left_LED(); TurnON_Launchpad_Right_Red_LED(); after(&t800ms, 2400000); PT_WAIT_UNTIL(pt, SWTimerExpired(&t800ms)); TurnOFF_Launchpad_Right_Red_LED(); TurnON_Launchpad_Left_LED(); after(&t800ms, 2400000); } PT_END(pt); } This looks quite similar to the first thread, only that there are now two places where the thread can be broken. However, overall, we have obtained a writing style which is easier to understand and more logical. 10:55 Conclusions All of the above code is provided as three examples: msp432-protothreads-1 msp432-protothreads-2 msp432-protothreads-3 The msp432-protothreads-3 contains the protothreads library. You can also consult additional documentation online: http://dunkels.com/adam/pt/ The bottom line - software does not have to be a hopeless ratsnest of logic. We can come up with better, more elegant ways to express programs: - using time - using threads