127. PWM Register Access Control

#include <iostream>

class PWMDriver {
private:
    int ccr_reg;  // Encapsulated register

public:
    PWMDriver() : ccr_reg(0) {}

    // Safe setter with saturation logic
    void setCCR(int val) {
        if (val > 100) {
            ccr_reg = 100;
        } else if (val < 0) {
            ccr_reg = 0;
        } else {
            ccr_reg = val;
        }
    }

    // Getter for read-only access
    int getCCR() const {
        return ccr_reg;
    }
};

int main() {
    int N;
    if (!(std::cin >> N)) return 0;

    PWMDriver driver;

    for (int i = 0; i < N; ++i) {
        int val;
        std::cin >> val;

        driver.setCCR(val);

        std::cout << "CCR: " << driver.getCCR() << std::endl;
    }

    return 0;
}

Explanation & Logic Summary:

In the original design, the ccr_reg was publicly accessible, allowing external code to write invalid values such as 150 or -20. In real embedded systems, this can lead to incorrect PWM behavior or undefined hardware states.

The solution applies standard embedded driver design principles:

  • Encapsulation: The CCR register is moved to private scope to prevent unsafe writes.
  • Controlled Interface: A public setCCR() method is introduced to manage updates.
  • Saturation Logic: Inputs are clamped to the valid hardware range [0, 100].

This guarantees that the internal state of the PWM driver always remains valid, regardless of application input.

Firmware Relevance & Real-World Context:

  • Hardware Safety: Writing invalid values to timer registers can cause signal lockups or damage connected power electronics.
  • Saturation vs Wraparound: Firmware commonly uses saturation logic instead of relying on integer overflow behavior.
  • Driver Abstraction: Real MCU drivers (e.g., STM32, AVR timers) expose APIs like setDutyCycle() rather than allowing direct register access, enforcing correctness at the driver boundary.

This problem reinforces essential Embedded C++ practices used in production firmware.

 

 

 

Loading...

Input

3 50 150 -20

Expected Output

CCR: 50 CCR: 100 CCR: 0