0

I have two DC motors that I want to shut off when the servo is at 140 degrees and then turn back on when the servo is back to 0 degrees. So like if servo == 140 motor 1 and 2 speed == 0. I am using an Arduino Uno and an Arduino motor shield. This is the code I got so far:

EDIT: This is what I got now but I keep getting an error say that servo_test was not declared in this scope. Not sure what is going on

#include <AFMotor.h>

#include <Servo.h>

Servo my_servo;

AF_DCMotor motor1(3);
AF_DCMotor motor2(4);

void setup() {
  my_servo.attach(9);
  motor1.setSpeed(130);
  motor2.setSpeed(130);

}

int angle;
int motor1pin = 3;
int motor2pin = 4;

void loop() {
  motor1.run(BACKWARD);
  motor2.run(BACKWARD);

  for (angle = 0; angle <= 140; angle += 1) {
    // command to move from 0 degrees to 140 degrees

    servo_test.write(angle); //command to rotate the servo to the specified angle

    if (angle == 0) {
      digitalWrite(motor2Pin, HIGH);
      digitalWrite(motor1Pin, HIGH);
    }
    if (angle == 140) {
      digitalWrite(motor2Pin, LOW);
      digitalWrite(motor1Pin, LOW);
    }

    delay(15);
  }

  for (angle = 140; angle >= 0; angle -= 1) {
    // command to move from 140 degrees to 0 degrees

    servo_test.write(angle); //command to rotate the servo to the specified angle

    if (angle == 0) {
      digitalWrite(motor2Pin, HIGH);
      digitalWrite(motor1Pin, HIGH);
    }
    if (angle == 140) {
      digitalWrite(motor2Pin, LOW);
      digitalWrite(motor1Pin, LOW);
    }

    delay(15);
  }

}
3
  • so, which line in the program puts the servo to 140 degrees? – jsotola Nov 28 '20 at 4:36
  • if (servo == 140) stop_motors(); is the kind of idiom you would use if servo was an input. But it's an output: you decide when it goes to 140°. You just have to stop the motors whenever you decide to move the servo to that position: my_servo.write(140); stop_motors();. – Edgar Bonet Nov 28 '20 at 10:32
  • 1
    an error say that servo_test was not declared -- this is right. The only servo object you declare is called my_servo. Just use that object, – Maximilian Gerhardt Nov 28 '20 at 20:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.