PWM Constructor Modes

#include <iostream>
#include <algorithm> // Used for std::max and std::min to clamp values

using namespace std;

class PWMController {
private:
    int frequency; // PWM frequency in Hz
    int duty;      // Duty cycle percentage (0–100)
    bool enabled;  // PWM output state (true = 1, false = 0)

    // Helper method to ensure duty cycle is always between 0 and 100
    int clampDuty(int d) {
        if (d < 0) return 0;
        if (d > 100) return 100;
        return d;
    }

public:
    // Constructor 1: Basic Initialization
    // Configures frequency, but starts disabled with 0% duty.
    PWMController(int freq) {
        frequency = freq;
        duty = 0;
        enabled = false;
    }

    // Constructor 2: Full Initialization
    // Configures frequency and duty, and enables the output immediately.
    PWMController(int freq, int dutyCycle) {
        frequency = freq;
        duty = clampDuty(dutyCycle);
        enabled = true;
    }

    // Updates the duty cycle with safety clamping
    void setDuty(int d) {
        duty = clampDuty(d);
    }

    // Disables the PWM output
    void disable() {
        enabled = false;
    }

    // Prints the state in the format: F=<frequency> D=<duty> EN=<0 or 1>
    void print() {
        cout << "F=" << frequency 
             << " D=" << duty 
             << " EN=" << (enabled ? 1 : 0) << endl;
    }
};

int main() {
    int mode;
    if (!(cin >> mode)) return 0;

    // We use a pointer or re-assignment logic to handle the different constructors.
    // In the provided snippet, we re-assign the temporary 'pwm' object.
    PWMController pwm(0); 

    if (mode == 1) {
        int f;
        cin >> f;
        pwm = PWMController(f);
    }
    else if (mode == 2) {
        int f, d;
        cin >> f >> d;
        pwm = PWMController(f, d);
    }

    int x;
    cin >> x;

    if (x == -1) {
        pwm.disable();
    } else {
        pwm.setDuty(x);
    }

    pwm.print();

    return 0;
}

Solving Approach

 

 

 

 

 

Upvote
Downvote
Loading...

Input

1 1000 50

Expected Output

F=1000 D=50 EN=0