53. Compile-Time Timer Reload

#include <iostream>
using namespace std;

// Compute timer reload at compile time (with rounding)
constexpr unsigned int computeReload(unsigned int clockHz,
                                     unsigned int intervalMs) {
    return (clockHz * intervalMs + 500) / 1000;
}

// Precomputed reload values for 1 ms, 10 ms, 100 ms
constexpr unsigned int RELOAD_TABLE[3] = {
    computeReload(1'000'000, 1),
    computeReload(1'000'000, 10),
    computeReload(1'000'000, 100)
};

int main() {
    int idx;
    cin >> idx;

    cout << RELOAD_TABLE[idx];
    return 0;
}

Explanation & Logic Summary:

  • Hardware timers require precise reload values for periodic interrupts
  • constexpr ensures all reload values are computed at compile time
  • The reload table is stored in Flash, not RAM
  • Rounding ensures timing accuracy
  • Runtime code only performs array indexing

Firmware Relevance & Real Embedded Meaning:

  • Timer reload values are fundamental to RTOS ticks, control loops, and sampling
  • Runtime division is slow and risky on MCUs
  • Compile-time computation ensures:
    • Deterministic timing
    • Zero runtime math
    • Zero RAM usage
    • High reliability in safety-critical firmware

This mirrors how real MCU HALs and RTOS kernels configure timers internally.

 

 

 

 

Loading...

Input

0

Expected Output

1000