CodeBlanks Logo Icon CodeBlanks

Summary - Embedded C++

Combine MMIO, free-standing and interrupts to write an LED blink app.

Summary - Embedded C++

In this group you saw the core embedded C++ tools: embedded system, MMIO, freestanding, interrupt and real-time. All ensure reliable operation on constrained hardware.

Now you will combine them in a volatile variable example. You will use volatile for shared variables and ISR-style flags together; this shows how embedded programs are built.

Volatile + flag

In an embedded program volatile variables both point to hardware registers and act as flags shared with the ISR. counter can be a counter, ready a flag; both must be volatile.

Example: volatile int counter = 0; volatile bool ready = false;. The assignment counter = 7; ready = true; signals that the ISR has finished and prepared data. The main loop checks ready and reads counter. Without volatile the compiler may do these accesses once and skip.

Practice Write volatile counter + flag

Define global volatile int counter = 0; and volatile bool ready = false;. In main write counter = 7;, ready = true; and std::cout << counter + (ready ? 1 : 0);.

Starter code

main.cpp
#include <iostream>

// Define the counter and ready volatile variables here

int main() {
    // Set counter to 7, ready to true and print the total
    return 0;
}

Sample solution

main.cpp
#include <iostream>

volatile int counter = 0;
volatile bool ready = false;

int main() {
    counter = 7;
    ready = true;
    std::cout << counter + (ready ? 1 : 0);
    return 0;
}

Expected output

8

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which keyword is essential for MMIO?

main.cpp
volatile std::uint32_t* reg = ...;
  • const
  • inline
  • static
  • volatile Correct answer

Explanation: volatile prevents the compiler from optimizing hardware access.

2 Complete the volatile pointer

Question
volatile std::uint32_t* ____ = reinterpret_cast<volatile std::uint32_t*>(&storage);
Answer
volatile std::uint32_t* reg = reinterpret_cast<volatile std::uint32_t*>(&storage);

Explanation: Write volatile std::uint32_t* reg = ...;; reg points to storage.

3 Match each tool to its trait

Term Meaning
embedded Constrained resources
MMIO Memory-mapped I/O
volatile Hardware access
real-time Fixed time

All lessons in Expert