5 years, 11 months ago.

Defining a Class (or multiple classes) that uses Different Pinouts (AnalogOut vs. PwmOut)

I am writing a library for controlling motors (interacting with a motor controller) and some of these require an AnalogOut, while others require PwmOut. However, other than this, everything else can be abstracted to a simple interface. Right now, I have two separate classes, one for analog and one for Pwm. However, I would like to combine them so that I can interact without them without caring which type they are (since it doesn't matter to the programmer once they are declared). How can I do this?

Simplification of what I have now in the header file:

motor controller

class PwmMotor {
    PwmOut _speedPin;
   
 
public:
    //!Creates PwmMotor and intializes
    PwmMotor(PinName speedPin);

    void speed(float n);  //send -100 to 100 (with 100 being full speed ahead, -100 being full back, and 0 being stopped
}

class PwmMotor {
    AnalogOut _speedPin;
   
 
public:
    //!Creates AnalogMotor and intializes
    AnalogMotor(PinName speedPin);

    void speed(float n);  //send -100 to 100 (with 100 being full speed ahead, -100 being full back, and 0 being stopped

}

The speed function basically just 'writes' to the speed controlling pin, and the function is literally the same for both AnalogOut and PwmOut, which means that literally nothing else in the library needs to change except how the speed pin is initialized.

I don't mind declaring one or the other/ using a different constructor when I create an instance of the class, but then when I pass it to another function, I have to tell that function what to expect, which means either more redundancy or changing that other code every time I switch types of motor controllers... also, I don't want every function to have to check which type it is (analog or pwm) before taking action.

Anyone know the right way to do this? Technically my program works right now, but I feel like there's a correct way to do this and I'm pretty sure my way is not it. I asked some friends and no one knew how to do this, so we felt like it might be a good opportunity to learn. Any ideas?

1 Answer

5 years, 11 months ago.

Probably the nicest way is to use templates. See for example here: http://www.cprogramming.com/tutorial/templates.html

Not the easiest stuff to get used to working with, but it can be useful if you want to do stuff like this the best way.

Accepted Answer