128. UART Baud Rate Validation

#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:

  • Encapsulates state by making baud_rate private.
  • Validates input using a whitelist of supported baud rates.
  • Implements fail-safe behavior by ignoring invalid configuration requests.
  • Preserves system availability by maintaining the last known good configuration.
  • Avoids dynamic memory and complex abstractions, ensuring predictability.

Firmware Relevance & Real-World Context:

  • UART baud rates are derived from fixed clock trees and dividers.
  • Invalid configurations can silently break communication.
  • Defensive driver APIs are critical in embedded systems where application code may be untrusted or error-prone.
  • Failing safely is often preferable to attempting recovery from an invalid hardware state.

This problem reinforces robust driver design, hardware-aware validation, and state protection, all of which are essential firmware engineering skills.

 

 

 

 

 

Loading...

Input

4 115200 500 19200 -1

Expected Output

Active: 115200 Active: 115200 Active: 19200 Active: 19200