Simple Motor Code (useful for debugging)

181017KA

Hellooooo

This actually took a while to get to (had to rebuild and learn some coolio things) but here’s the tested simple-motor-code. It essentially sets motor speed based on what you type into the Serial Monitor… pretty sweet until I realized I wasn’t going to need that function lol.

//10/17/18
//okie dokie this artichokie finally works pretty sweet so here it is: basically it just sets the motor speeds (whoop!)

class Motor{
  private:
  int pin_enable; //this is the thing that you set the speed with
  int pin_forward;    //basically each motor has two of these pins,
  int pin_backward;    //and you use them to reverse polarity and switch direction

  public:
  Motor(int enable, int one, int two){
    pin_enable = enable;
    pin_forward = one;
    pin_backward = two;
    //in the old code they essentially combined these last two steps with something fancy
    //oh well, this is easier to understand lol
  }

  void motorSpeed(int Speed){
   if(Speed > 0 ||  Speed == 0){ //here, I'm asking which way to set the polarity, with the idea being that I can input pos. or neg. speeds into the function
     digitalWrite(pin_forward, HIGH);
     digitalWrite(pin_backward, LOW);
     analogWrite(pin_enable, Speed);
  }
    else{
     digitalWrite(pin_forward, LOW);
     digitalWrite(pin_backward, HIGH);
     analogWrite(pin_enable, -Speed);
    }
  }
};

  void setSpeeds(int bothSpeed){
    right_motor.motorSpeed(bothSpeed);
    left_motor.motorSpeed(bothSpeed);
  }

//Reverse Polarity protector is plugged into Pin 12 on the MEGA shield
Motor right_motor(10, 6, 5);
Motor left_motor(11, 4, 3);
char SIDE;
int right_speed;
int left_speed;


void setup() {
  Serial.begin(9600);
  Serial.println("Starting up...");
}


void loop() {
   //this is the loop that checks Serial availability and then for motor speed inputs
  if (Serial.available() > 0) { //check that the Serial Monitor works
     char SIDE = Serial.read(); //read a character that will determine which motor speed to set in next if-loops
     int in = Serial.parseInt(); //now read the motor speed
     if (SIDE == 'R'){         //R designates the right motor
      right_motor.motorSpeed(in);
      right_speed = in;
     }
     else if (SIDE == 'L') {  //L designates the left motor
      left_motor.motorSpeed(in);
      left_speed = in;
     }
     else if (SIDE == 'B'){
      setSpeeds(in);
      right_speed = in;
      left_speed = in;
     
     }

    Serial.println(right_speed, DEC); //print out the new speeds (ie. check that the correct one was changed)
    Serial.println(left_speed, DEC);
    delay(10);
  }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *