GMU:Functions and Classes (Arduino): Difference between revisions

From Medien Wiki
Line 108: Line 108:




[[File:OOPARD8.jpg]]


// Defining a class for motor control
<br>
class MotoMamaMotor {
<br>
 
 
  private: // the following definitions are only of „internal use“ for the class itself
    int forwardPin; //Every MotoMamaMotor type Object has its own forwardPin
    int reversePin;
    int throttlePin;
 
  public: // the following qualities and methods are visible from the outside.
    //  This setup-Function has to be called before using the motor control
    void setup(int newForwardPin, int newReversePin, int newThrottlePin) {
      // we remember the pins for future use
      forwardPin = newForwardPin;
      reversePin = newReversePin;
      throttlePin = newThrottlePin;
      // and at the same time we initialize the outputs !
      digitalWrite(throttlePin, LOW); //  so that the motors don’t spin directly from the beginning ..
      pinMode(forwardPin, OUTPUT);
      pinMode(reversePin, OUTPUT);
      pinMode(throttlePin, OUTPUT);
    }
 
    // this Function allows to control the motor speed
    void setThrottle (int newThrottle) {
      if (newThrottle > 0) { // should it spin forwards or backwards?
        // spin forwards
        digitalWrite(reversePin, LOW);
        digitalWrite(forwardPin, HIGH);
      } else {
        // spin backwards
        digitalWrite(forwardPin, LOW);
        digitalWrite(reversePin, HIGH);
      }
      // adjust the speed:
      analogWrite(throttlePin, newThrottle);
    }
};
 
// create two separate MotoMamaMotor type Objects (leftMotor, rightMotor). They can be used as normal variables.
MotoMamaMotor leftMotor;
MotoMamaMotor rightMotor;
 
void setup() { // this is our „main“ setup Function
  leftMotor.setup(3, 4, 5); // assign the pin numbers for each motor in the setup Function: setup(int newForwardPin, int newReversePin, int newThrottlePin)
  rightMotor.setup(6, 7, 8);
};
 
void loop() { // this is our „main“ loop Function where concrete actions are executed. For example:
  // Start backwards, slow down and accelerate forwards
  for (int i = -255, i <= 255; i++) {
    leftMotor.setThrottle(i);
    rightMotor.setThrottle(i);
  };
  // Start forwards, slow down and accelerate backwards
  for (int i = 255, i >= -255; i--) {
    leftMotor.setThrottle(i);
    rightMotor.setThrottle(i);
  };
};


==Organizing classes in separate files==
==Organizing classes in separate files==