Confirmation on Private objects in classes

  arduino, c++, class, inheritance, servo

So I was browsing around for awnsers and I think I found a solution, I just want to be sure I understand it correctly. And also if I use the wrong terminology please feel free to correct me.

So the short version of the story, I would like to create a class for each of the 4 servo’s I have on my robot arm. So initially i was trying to figure out how to create a unique name for each servo object, so that I dont accidentally overwrite a command or send the wrong motor moving. But when i went back into my code, I saw I created a servo as private in the class.


class myServo {
  // My understanding of how this is working (declaring one name for the servo, but then decaring multiple instances), is that because the Servo Object servo, is private, it only "exists" within this class. THe main loop cannot see it so you can have multiple myServo classes with servo Objects in each, but they can only be seen by their respective class objects. That being said, you can only address them via class methods
  private:  
  Servo servo;
  
  public:

  void init(int servoPin){
    pinMode(servoPin, OUTPUT);
    servo.attach(servoPin);
  }

  void write(int angle){
    servo.write(angle);
  }
  

  int currentPos, minLimit, maxLimit;

  void setCurrentAngleToMinLimit(){  currentPos = minLimit;  };
  void setCurrentAngleToMaxLimit(){  currentPos = maxLimit;  };

  void angleMoveIncremental(int targetAngle){
    if(currentPos + targetAngle >= minLimit && currentPos + targetAngle <= maxLimit){
      currentPos = targetAngle;
    }else{
      Serial.println("Error on andgleMoveIncremental, angle exceeds bounds");
    }
  };

  void angleMoveAbsolute( int targetAngle){
    if(targetAngle >= minLimit && targetAngle <= maxLimit){
      currentPos = targetAngle;
    }else{
      Serial.println("Error on angleMoveAbsolute, angle exceeds limit check");
    }
  };
  
};

    
myServo servoHead;
myServo servoBase;

servoHead.init(12);
servoBase.init(11);

My question basically boils down to this, when Im declaring a Servo object like this, is the name "servo" only visible to the class and class members? ie, Ill have multiple servo objects names "servo" but it wont matter cause because their contained in the class? And the only way to work with the Servo objects like this is to create Class Members, even if their literally just putting the same command I would use in my main loop to direct a servo directly, but just in the class and referring to the Object name? ie:


class myServo{

private: 
Servo anotherServo;

public:
void attach(int anotherServoPin){
anotherServo.attach(anotherServoPin);
}

}

Thanks so much! 🙂

Source: Windows Questions C++

LEAVE A COMMENT