简体   繁体   中英

Arduino servo and DC motor not working properly

I'm very new to the Arduino world but I have some experience of programming in other language.

I'm trying to make my first robot car, I have 2 DC motors connected to a L298N module, all connected to a 9V battery and an Arduino Uno.

The DC motors are connected to port 5,6,7 for motor 1 and port 8,9,10 for motor 2.

The code is working fine to go forward and back.

At this stage I want to connect a DC servo, which I connected to port 13, to the 5 volt and to ground, and here is the issue:

With the following code only one DC motor and servo are moving, but the second DC motor is stuck!

I notice that if I remove from the void setup() the command servo_motor.attach(13); both DC motors are running.

It should move the servo and both DC motors...

Any reason why?

Thanks for help.

#include <Arduino.h>
#include <Servo.h>

const int mot2 = 10;
const int ava2 = 9;
const int ind2 = 8;
const int mot1 = 5;
const int ava1 = 6;
const int ind1 = 7;
Servo servo_motor;  // create servo object to control a servo
int pos = 0;

void moveForward() {
  Serial.print("Going Forward\n");

  // turn on motor A
  digitalWrite(ava1, HIGH);
  digitalWrite(ind1, LOW);

  // set speed to 200 out of possible range 0~255
  analogWrite(mot1, 100);

  // turn on motor B
  digitalWrite(ava2, LOW);
  digitalWrite(ind2, HIGH);

  // set speed to 200 out of possible range 0~255
  analogWrite(mot2, 100);

  delay(2000);
}

void moveBack() {
  Serial.print("Going BACK\n");

  // turn on motor A
  digitalWrite(ava1, LOW);
  digitalWrite(ind1, HIGH);

  // set speed to 200 out of possible range 0~255
  analogWrite(mot1, 250);

  // turn on motor B
  digitalWrite(ava2, HIGH);
  digitalWrite(ind2, LOW);

  // set speed to 200 out of possible range 0~255
  analogWrite(mot2, 250);
 
  delay(2000);
}

void moveServo() {
  for (pos = 0; pos <= 180; pos += 1) {
    servo_motor.write(pos);             
    delay(15);                       
  }
  for (pos = 180; pos >= 0; pos -= 1) {
    servo_motor.write(pos);             
    delay(15);                       
  }
}


void setup() {
  Serial.begin(9600);
  servo_motor.attach(13); //  why if i remove this both DC motor work and if i put only one DC motor work??
  pinMode(mot2, OUTPUT);
  pinMode(ava2, OUTPUT);
  pinMode(ind2, OUTPUT);
  pinMode(mot1, OUTPUT);
  pinMode(ava1, OUTPUT);
  pinMode(ind1, OUTPUT);
}

void loop() {
  moveServo();
  delay(2000);
  moveForward();
  delay(2000);
  moveBack();
}

Have you tried to use another pin instead of pin 13 to control servo? Pin 13 is not recommend to control the servo because there is a LED connected to pin 13. Try pin 3 because it has PWM and it has no pull up resistor connected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM