Why not use printf all the time instead of pc.write?

Mostly for speed reasons! While incredibly powerful, printf can take milliseconds to print something, whereas pc.write takes microseconds. If you need to send a lot of information in a short period of time, you are better off using pc.write.

Consider the following example code:

#include "mbed.h"

static BufferedSerial pc(USBTX, USBRX);
Timer timeElapsed;

using namespace std::chrono;

int main()
{
    timeElapsed.start();
    
    char msg[] = "Hello World!\\n";
    pc.write(msg, sizeof(msg));
    
    timeElapsed.stop();

    // print time elapsed
    printf("The time taken was %llu milliseconds\\n", duration_cast<milliseconds>(timeElapsed.elapsed_time()).count());
    printf("The time taken was %llu microseconds\\n", duration_cast<microseconds>(timeElapsed.elapsed_time()).count());

    timeElapsed.reset();
    timeElapsed.start();
    printf("Hello World!\\n");
    timeElapsed.stop();

    printf("The time taken was %llu milliseconds\\n", duration_cast<milliseconds>(timeElapsed.elapsed_time()).count());
    

    while(1);
}

The serial monitor will output something that looks like this:

Hello World!
The time taken was 0 milliseconds
The time taken was 90 microseconds
Hello World!
The time taken was 14 milliseconds

Using pc.write took 90 microseconds whereas using printf took 14 milliseconds. That’s 155.55 times longer!

State Machine Best Practices

C++ Variable Keywords

Keyword Definition When used
volatile avoid compiler optimizations because the variable could be updated at any time when variable is shared between ISR and main loop
static re-use existing variable if already defined use as a local variable in a state machine