11. UART Write Overloading

#include <iostream>
#include <string>
#include <cstdint>
#include <cstddef>

using namespace std;

// Overload for sending a single byte value
void write(uint8_t byteValue) {
    cout << static_cast<unsigned int>(byteValue);
}

// Overload for sending a text string
void write(const string& str) {
    cout << str;
}

// Overload for sending a buffer of bytes
void write(const uint8_t* buffer, size_t length) {
    for (size_t i = 0; i < length; i++) {
        cout << static_cast<unsigned int>(buffer[i]);
        if (i + 1 < length) {
            cout << " ";
        }
    }
}

int main() {
    int mode;
    cin >> mode;

    if (mode == 1) {
        unsigned int byteValue;
        cin >> byteValue;
        write(static_cast<uint8_t>(byteValue));
    }
    else if (mode == 2) {
        string s;
        cin >> s;
        write(s);
    }
    else if (mode == 3) {
        int n;
        cin >> n;

        uint8_t buffer[100];
        for (int i = 0; i < n; i++) {
            unsigned int temp;
            cin >> temp;
            buffer[i] = static_cast<uint8_t>(temp);
        }
        write(buffer, static_cast<size_t>(n));
    }

    return 0;
}

Explanation & Logic Summary

This program demonstrates C++ function overloading in the context of a UART-style transmission interface.

Three overloaded write() functions are implemented:

  • write(uint8_t)
     Sends a single numeric byte and prints it as an integer.
  • write(const string&)
     Sends a text string and prints it exactly as received.
  • write(const uint8_t*, size_t)
     Sends a buffer of raw bytes and prints each byte as a number separated by spaces.

For buffer transmission, input values are first read as integers and then stored into a byte buffer to ensure they are treated as raw numeric bytes, not ASCII characters.

The parameter types are intentionally distinct to guarantee unambiguous overload resolution across different compilers.

 

Firmware Relevance & Real-World Context

In real embedded systems, UART/SPI/I2C drivers commonly support:

  • Transmitting a single byte (commands, register access)
  • Transmitting strings (debug logs, console output)
  • Transmitting raw byte buffers (protocol packets, sensor frames) 

This problem evaluates:

  • Correct use of C++ function overloading
  • Safe handling of byte-oriented data
  • Awareness of fixed-width integer types
  • API design skills relevant to firmware development

 

 

 

Loading...

Input

1 0

Expected Output

0