Pre-class Assignment

Announcements

Learning Outcomes

By the end of this lecture, you should be able to...

Lecture Content

<aside> 💡 This is not content that is required to be implemented for Lab 1 (aside from the short line about timers at the end of the lecture). We’ll be using this for Lab 2 which will be released next week.

</aside>

Blocking vs. Non-blocking Operations

The way that we’ve implemented our code for the keypad, we are using what is called a blocking operation. We are waiting for a key press, and our code can’t do anything else while we are waiting:

// get keypress
char buff;
pc.read(&buff,1);
pc.write(&buff,1);

This makes sense in this particular case because we only have one thing to do! However, this might not be desirable in other circumstances. For example, let’s say we also want to toggle an LED once every other second:

#include "mbed.h"

#define WAIT_TIME_MS 500 
DigitalOut led1(LED1);

char buff;

int main()
{
    // needed to use thread_sleep_for in debugger
    // your board will get stuck without it :(
    #if defined(MBED_DEBUG) && DEVICE_SLEEP
        HAL_DBGMCU_EnableDBGSleepMode();
    #endif
    
    printf("This is the bare metal blinky example running on Mbed OS %d.%d.%d.\\n", MBED_MAJOR_VERSION, MBED_MINOR_VERSION, MBED_PATCH_VERSION);

    while (true)
    {
				pc.read(&buff,1);
				pc.write(&buff,1);
        led1 = !led1;
        thread_sleep_for(WAIT_TIME_MS);
    }
}

If we tried to read a character in the same loop, our loop would be very slow in toggling the LED (if it ever did!). We need some way to implement non-blocking code.

One way to handle this issue is to use a ticker instead.