#include <iostream>
class UARTDriver {
private:
int baud_rate;
public:
UARTDriver() : baud_rate(9600) {}
void setBaudRate(int req) {
switch (req) {
case 9600:
case 19200:
case 115200:
baud_rate = req;
break;
default:
// Invalid request: retain previous valid state
break;
}
}
int getBaudRate() const {
return baud_rate;
}
};
int main() {
int N;
if (!(std::cin >> N)) return 0;
UARTDriver driver;
for (int i = 0; i < N; ++i) {
int req;
std::cin >> req;
driver.setBaudRate(req);
std::cout << "Active: " << driver.getBaudRate() << std::endl;
}
return 0;
}
Explanation & Logic Summary:
The original implementation exposed the UART baud rate directly, allowing invalid values to propagate into hardware clock configuration. This is unsafe in embedded systems where peripherals only support discrete, hardware-defined settings.
The refactored design:
baud_rate private.Firmware Relevance & Real-World Context:
This problem reinforces robust driver design, hardware-aware validation, and state protection, all of which are essential firmware engineering skills.
Input
4 115200 500 19200 -1
Expected Output
Active: 115200 Active: 115200 Active: 19200 Active: 19200