7 years, 4 months ago.

Unused pins in constructor

Hello all,

I created a small class for PWM motor control. In the constructor the hardware pins are defined like this:

DigitalOut dirPin, brakePin;
AnalogIn curPin;

motor2::motor2( PinName pwmPinName, PinName dirPinName, PinName brakePinName, PinName curPinName )
 : pwmPin( pwmPinName ), dirPin( dirPinName ), brakePin( brakePinName ), curPin( curPinName )

This works fine.

But: I don't need the brake and the cur pin in every of my applications. On all my applications i use in minimum 2 times this class and in some 1 with and 1 without. When I initialize these parameters with NC my application crashs.

How can I initialize this correctly?

PS: please excuse my bad english.

1 Answer

7 years, 4 months ago.

You can use NC as PinName, but you are not allowed to use a DigitalOut or DigitalIn variable if it has been instantiated with NC as the PinName.

I have used the following solution for this problem:

//constructor

TextLCD_SPI_N::TextLCD_SPI_N(SPI *spi, PinName cs, PinName rs, LCDType type, PinName bl, LCDCtrl ctrl) :
                             TextLCD_Base(type, ctrl),  _spi(spi),   _cs(cs),  _rs(rs) {      
        
....

  // The hardware Backlight pin is optional. Test and make sure whether it exists or not to prevent illegal access.
  if (bl != NC) {
    _bl = new DigitalOut(bl);   //Construct new pin 
    _bl->write(0);              //Deactivate    
  }
  else {
    // No Hardware Backlight pin       
    _bl = NULL;                 //Construct dummy pin     
  }  
 }

....

make sure that pin is never used in the code without testing its validity:

// Set BL pin
void TextLCD_SPI_N::_setBL(bool value) {
    if (_bl) {
        _bl->write(value);   
    }    
}  

The DigitalOut pin must be declared in the class header like this:

...
//Backlight
    DigitalOut *_bl;    
...