UART Baud Rate Validation

#include <iostream>

enum class BAUD{
    LOW = 9600,
    MEDIUM = 19200,
    HIGH = 115200
};  

class UARTDriver {
    private:
        BAUD baud_rate;
public:
    // TODO: This member must not be publicly writable.
    // TODO: Only allow discrete hardware-supported baud rates.

    UARTDriver() : baud_rate(BAUD::LOW) {}

    // TODO: Add a validating setter.
void set_baud(int req){
    switch(req){
        case 9600: baud_rate = BAUD::LOW; break;
        case 19200: baud_rate = BAUD::MEDIUM; break;
        case 115200: baud_rate = BAUD::HIGH; break;
        default: break; // or ignore
    }
}
    // TODO: Add read-only access to the current baud rate.
    long get_baud() const{
        return static_cast<long>(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);

        // TODO: Replace direct access with a validating API.
        driver.set_baud((req));

        std::cout << "Active: " << driver.get_baud() << std::endl;
    }

    return 0;
}

Solving Approach

 

 

 

 

 

Upvote
Downvote
Loading...

Input

4 115200 500 19200 -1

Expected Output

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