#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:
setCCR() method is introduced to manage updates.[0, 100].This guarantees that the internal state of the PWM driver always remains valid, regardless of application input.
Firmware Relevance & Real-World Context:
setDutyCycle() rather than allowing direct register access, enforcing correctness at the driver boundary.This problem reinforces essential Embedded C++ practices used in production firmware.
Input
3 50 150 -20
Expected Output
CCR: 50 CCR: 100 CCR: 0