14. UART Initialization Defaults

#include <iostream>
using namespace std;
 
// baud is required
// parity default = 'N' (no parity)
// stopBits default = 1
void initUART(int baud, char parity = 'N', int stopBits = 1) {
    cout << baud << " " << parity << " " << stopBits;
}
 
int main() {
    int baud, mode;
    cin >> baud >> mode;
 
    if (mode == 0) {
        // only baud given, use both default parameters
        initUART(baud);
    } else if (mode == 1) {
        char parity;
        cin >> parity;
        // custom parity, default stop bits
        initUART(baud, parity);
    } else if (mode == 2) {
        char parity;
        int stopBits;
        cin >> parity >> stopBits;
        // custom parity and stop bits
        initUART(baud, parity, stopBits);
    }
 
    return 0;
}

Explanation & Logic Summary:

  • Default arguments allow you to call initUART with:
    • only baud (uses 'N' and 1)
    • baud parity (uses default stopBits)
    • or all parameters explicitly.
  • The defaults are specified in the function parameter list, so when arguments are omitted, those defaults are used automatically.
  • This reduces the need for multiple overloads while keeping the API flexible.
     

Firmware Relevance & Real-World Context:

  • UART configuration in embedded systems often includes baud rate, parity, and stop bits.
  • Most applications use standard defaults (e.g., 9600 8N1), while some special cases override parity or stop bits.
  • Default arguments allow a clean, single function interface for both simple and advanced use cases.
  • This pattern mirrors real HAL APIs, where typical settings are easy to call, but full control is still available when needed.
     

 

 

 

 

Loading...

Input

9600 0

Expected Output

9600 N 1