65. Compile-Time Timer Reload

In many microcontrollers, periodic interrupts (1 ms, 10 ms, 100 ms, etc.) are generated using a hardware timer reload value.

This value must be computed using:

reload = timerClockHz × intervalSec

Since this value must be exact, firmware often computes it at compile time using constexpr.
Incorrect reload values cause jitter, drift, or system failure.

Your job is to compute the correct timer reload count at compile time for different timer intervals.

What you must do:

  • Define a constexpr function named computeReload
    • It must compute:
      • (clockHz × intervalMs + 500) / 1000 
  • This converts milliseconds to seconds
  • +500 is used for integer rounding
  • Define a constexpr array named RELOAD_TABLE
    • It must contain exactly 3 compile-time reload values, in this order:
      1. Reload value for 1 ms
      2. Reload value for 10 ms
      3. Reload value for 100 ms
  • All values must be computed using computeReload
  • Use:
    • timerClockHz = 1'000'000 (1 MHz)

Program input:

  • The user enters an integer index:
    • 0 → 1 ms reload
    • 1 → 10 ms reload
    • 2 → 100 ms reload
  • Input is guaranteed to be valid (0–2)

Program output:

  • Print the reload value from RELOAD_TABLE[index]

 

Example 1

Input:

1

Output:

10000

 

Example 2

Input:

2

Output:

100000

 

Constraints:

  • computeReload must be declared constexpr
  • RELOAD_TABLE must be declared constexpr
  • No runtime math except array indexing
  • Use integer arithmetic only
  • Output must match exactly

 

 

 

Need Help? Refer to the Quick Guide below

In Embedded C, we often use macros (#define) to perform math before the code runs (e.g., #define PRESCALER (CLK / BAUD)).

In C++, constexpr (Constant Expression) allows you to write standard C++ functions and variables that the compiler evaluates during compilation.

This means complex calculations (like generating CRC tables or converting units) happen on the developer's PC, and only the final result is burned into the microcontroller's Flash memory.

Syntax & Usage

1. Variables (True Constants)

Unlike const (which just means "read-only" and might typically sit in RAM or Flash), constexpr guarantees the value is known at compile time.

// C-Style
#define MAX_VOLTAGE 3.3

// C++ Style
constexpr float MAX_VOLTAGE = 3.3f;
constexpr float THRESHOLD = MAX_VOLTAGE / 2.0f; 
// Compiler calculates 1.65f and stores it directly. No runtime division.

2. Functions (The Powerhouse)

You can write functions that execute during compilation.

// Calculates factorial at compile-time
constexpr int factorial(int n) {
    return (n <= 1) ? 1 : (n * factorial(n - 1));
}

// Usage
// The compiler effectively writes: int buf_size = 120;
int buf_size = factorial(5); 

3. If/Loops (C++14 onwards)

Modern constexpr supports standard logic.


constexpr uint32_t calculate_prescaler(uint32_t sysclk, uint32_t target_freq) {
    uint32_t div = sysclk / target_freq;
    if (div > 0xFFFF) return 0xFFFF; // Clamp to 16-bit
    return div;
}

Comparison: The Evolution of Constants

Feature#defineconstconstexpr
MechanismText Replacement.Read-Only Variable.Compile-Time Calculation.
Type SafetyNone.Strong.Strong.
DebugHard (Symbol usually lost).Easy.Easy (if runtime fallback).
MemoryNone (Code literal).RAM or Flash.None (Code literal).

Relevance in Embedded/Firmware

1. Zero-Overhead Lookup Tables

Instead of hardcoding a 256-byte CRC table or Sine Wave array (which is error-prone to type manually), you can write a constexpr function to generate it. The compiler fills the array in Flash for you.

struct Table { uint8_t data[256]; };

constexpr Table generate_crc() {
    Table t = {};
    // ... Fill t.data logic ...
    return t;
}

// Table is generated during compilation and stored in Flash (.rodata)
constexpr Table crc_table = generate_crc(); 

2. Safe Register Math

Calculating bitmasks or clock dividers often involves complex shifts and divisions. Using macros (#define) is messy and error-prone. constexpr functions allow you to write readable logic with validation checks (asserts) that run at compile time.

3. Static Assertions

You can use constexpr values in static_assert to prevent invalid configurations from even compiling.

constexpr int BUFFER_SIZE = 128;
static_assert(BUFFER_SIZE % 8 == 0, "Buffer must be aligned to 8 bytes");

Common Pitfalls (Practical Tips)

PitfallDetails
❌ Runtime Usage

A constexpr function can be called at runtime if the inputs aren't constants.

int x = 5; factorial(x); runs on the CPU, not the compiler.

❌ DebuggingYou cannot "step through" a constexpr calculation in the debugger because it happened before the program started.
❌ Complexity LimitCompilers place limits on how many steps a constexpr function can take (recursion depth or loop count) to prevent the compilation from hanging forever.
✅ Use constevalIn C++20, the keyword consteval was added. It forces immediate evaluation and throws an error if it attempts to run at runtime.