Let's Make Robots!

control 2 motors with arduino motor shield

Hey guys I have a arduino motor shield from adafruit and I want a code for it so that i can control two motors from it. So please could you post a code for it. Also could you tell me that can I connect 2 servos and 2 motors on the shield at one time without having any problem.

Thanks for your help.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

I'm not sure what you mean by simultaneously, all code is executed inline, one instruction at a time. It does it so fast though, you might think that the commands are simultaneous.

Here is some function code for 4 motors I use in some of my robots.

AF_DCMotor motor1(1, MOTOR12_64KHZ); // create motor #1, 64KHz pwm
AF_DCMotor motor2(2, MOTOR12_64KHZ); // motor #2
AF_DCMotor motor3(3, MOTOR12_64KHZ); // motor #3
AF_DCMotor motor4(4, MOTOR12_64KHZ); // motor #4

void go() {
  Serial.println("All motors ahead - fast");  
  motor1.run(FORWARD);
  motor2.run(FORWARD);
  motor3.run(FORWARD);
  motor4.run(FORWARD);  
  motor1.setSpeed(255);
  motor2.setSpeed(255);
  motor3.setSpeed(255);
  motor4.setSpeed(255);
}

void backup() {
  Serial.println("All motors backward - fast");
  motor1.run(BACKWARD);
  motor2.run(BACKWARD);
  motor3.run(BACKWARD);
  motor4.run(BACKWARD);
  motor1.setSpeed(255);
  motor2.setSpeed(255);
  motor3.setSpeed(255);
  motor4.setSpeed(255);
}

void left() {
  Serial.println("Pivot left");
  motor1.run(BACKWARD);
  motor2.run(BACKWARD);
  motor3.run(FORWARD);
  motor4.run(FORWARD);
  motor1.setSpeed(255);
  motor2.setSpeed(255);  
  motor3.setSpeed(255);
  motor4.setSpeed(255);
}

void right() {
  Serial.println("Pivot right");
  motor1.run(FORWARD);
  motor2.run(FORWARD);
  motor3.run(BACKWARD);
  motor4.run(BACKWARD);
  motor1.setSpeed(255);
  motor2.setSpeed(255);  
  motor3.setSpeed(255);
  motor4.setSpeed(255);
}

void halt() {
  uint8_t i;
  for (i=255; i!=0; i--) {
    motor1.setSpeed(i);
    motor2.setSpeed(i);
    motor3.setSpeed(i);
    motor4.setSpeed(i);
    delay(10);
    }
   Serial.println("All motors stop");
   motor1.run(RELEASE);
   motor2.run(RELEASE);
   motor3.run(RELEASE);
   motor4.run(RELEASE);   
}

void avoidLeft() {
  halt();
  backup();
  delay(1500);
  left();
  delay(900);
}

void avoidRight() {
  halt();
  backup();
  delay(1500);
  right();
  delay(900);

}

 

That was exactly what I needed to get me started with my first wall avoiding robot.

  Simply read all the pages on the Use It for the shield on the Adafruit website.

 

http://www.ladyada.net/make/mshield/use.html

 

However the site does not tell that how can i control '2' motors simultaneously. So I would like to have a code for controlling 2 motors simultaneously - First both ahead, then one forward and one behind, then both the other way and at last both backward.