PWM Register Access Control

#include <iostream>

class PWMDriver {
private:
    // Encapsulated register: cannot be accessed directly from outside the class
    int ccr_reg;

public:
    // Constructor initializes the register to a safe default
    PWMDriver() : ccr_reg(0) {}

    /**
     * @brief Sets the CCR value using saturation logic.
     * Ensures the hardware register stays within the valid range [0, 100].
     * @param value The requested duty cycle ticks.
     */
    void set_ccr(int value) {
        if (value > 100) {
            ccr_reg = 100;
        } else if (value < 0) {
            ccr_reg = 0;
        } else {
            ccr_reg = value;
        }
    }

    /**
     * @brief Getter to read the current register value.
     * @return The current value of ccr_reg.
     */
    int get_ccr() const {
        return ccr_reg;
    }
};

int main() {
    int N;
    // Read the number of test inputs
    if (!(std::cin >> N)) return 0;

    PWMDriver driver;

    for (int i = 0; i < N; ++i) {
        int request_val;
        if (std::cin >> request_val) {
            // Use the safe setter to update the register
            driver.set_ccr(request_val);

            // Access the value via the getter for output
            std::cout << "CCR: " << driver.get_ccr() << std::endl;
        }
    }

    return 0;
}

Solving Approach

 

 

 

 

 

Upvote
Downvote
Loading...

Input

3 50 150 -20

Expected Output

CCR: 50 CCR: 100 CCR: 0