76. GPIO Pin Operator Overload

#include <iostream>
using namespace std;

// Define GPIO logic levels
enum class Level {
    LOW  = 0,
    HIGH = 1
};

class GpioPin {
private:
    Level level;

public:
    // Constructor initializes pin level
    explicit GpioPin(Level l) : level(l) {}

    // Write new pin level
    GpioPin& operator=(Level l) {
        level = l;
        return *this;
    }

    // Read pin level as integer (0 or 1)
    operator int() const {
        return static_cast<int>(level);
    }
};

int main() {
    int init, next;
    cin >> init >> next;

    GpioPin pin(static_cast<Level>(init));
    pin = static_cast<Level>(next);

    cout << pin;
    return 0;
}

Explanation & Logic Summary

  • The GPIO pin stores exactly one state: Level
  • operator= simulates writing a value to a hardware pin
  • operator int() simulates reading the pin value
  • enum class enforces type safety and prevents invalid states
  • No side effects, timing logic, or hardware dependencies are introduced

Firmware Relevance & Real-World Context

This pattern mirrors how GPIOs are modeled in real firmware:

  • Hardware Abstraction Layers (HAL)
  • RTOS-based GPIO drivers
  • Embedded simulation and unit testing
  • Peripheral modeling in C++ firmware frameworks

Using operator overloading for GPIO access enables clear, expressive, and maintainable embedded code, which is a common practice in modern embedded C++ development.

 

 

 

 

Loading...

Input

0 1

Expected Output

1