Hi, I'm trying to create a code that makes two DC motors run over 5 seconds, and after that action is completed I want the motors to stop and rotate two servo motors over 180 degrees so that they can pull a trigger. I'm unsure what part of my code is wrong, I'm trying to use Booleans to define state functions that represent the actions I described previously.
#include <Servo.h>
// Define pins for L298N
int enA = 9;
int in1 = 8;
int in2 = 7;
int enB = 6;
int in3 = 5;
int in4 = 4;
//Variable that moves the servos
int pos = 0;
// Define pins for servos
int servoPin1 = 11;
int servoPin2 = 10;
// Create servo objects
Servo servo1;
Servo servo2;
// Set up a Boolean variable to track whether DC motors have completed their action
bool dcMotorsCompleted = false;
void setup() {
// Initialize motor pins as outputs
pinMode(enA, OUTPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(enB, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
// Initialize servo pins
servo1.attach(servoPin1);
servo2.attach(servoPin2);
}
void loop() {
// Check if DC motors have completed their action
if (!dcMotorsCompleted)
{
// Run motors for 5 seconds
analogWrite(enA, 255);
analogWrite(enB, 255);
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
delay(5000);
// Stop motors
analogWrite(enA, 0);
analogWrite(enB, 0);
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, LOW);
delay(5000);
// Set the Boolean variable to true
dcMotorsCompleted = true;
}
// If DC motors have completed their action, move the servo motors
if (dcMotorsCompleted) {
for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
servo1.write(pos);
servo2.write(pos);
delay(15); // tell servo to go to position in variable 'pos' // waits 15ms for the servo to reach the position
}
}
}
Oh okay, here is the circuit, I'm using an L298N to control both of my DC motors, they are connected to pins 9,8,7,6,5,4.
Here is a link that explains the interface: https://lastminuteengineers.com/l298n-dc-stepper-driver-arduino-tutorial/
To control the servos I'm using a breadboard to connect two servos, the pins to control the servos are directly connected to the Arduino, they are pins 11 and 10. However to power the servos I connected the red and brown cables from each servo to the breadboard and I'm planning to put a second battery also connected to the breadboard to power the servos.
Oh that makes sense, thanks. Do you think there is something wrong with the code though? I want it to first make both DC motors run over 5 seconds, then stop. And after it stops I want it to make rotate both servos over 180 degrees. When I tried it with the code that I sent, it just made the DC motors work but the servos didn’t do anything