I'm working on a robot car project using an ESP32 Devkit V1 (likely a generic dev board). We have 2 DC motors for moving the robot and a servo motor for a lifting mechanism.
I made a program to turn the servo motor (SG90 - non-continuous) to a given angle. The program worked fine. and the servo moved as expected.
I already had my main program made to make the robot move. This is done by giving PWM pulses to the ENA and ENB pin values of the L298n motor drivers, which change the DC motor speeds. This program works fine as well.
Code: Select all
//L298N speed change
analogWrite(ENA, speedA);
analogWrite(ENB, speedB);
However, things changed when I tried to add the servo code to the main program. I'm moving the servo using <ESP32Servo.h> with the following code:
Code: Select all
// Define the servo pin
const int servoPin = 32;
// Create a Servo object
Servo myServo;
void Setup() {
Serial.begin(115200);
// Attach the servo to the servo pin
myServo.attach(servoPin);
}
void moveServoToAngle(int angle) {
// Check if the input is a valid angle
if (angle >= 0 && angle <= 180) {
// Move the servo to the specified angle
myServo.write(angle);
Serial.print("Moving to ");
Serial.print(angle);
Serial.println(" degrees");
delay(500);
}
}
What I figured out
After some testing and experimentation, I realized that once the analogWrite() is called on any GPIO pin (in this case, pins for ENA and ENB), the servo.write() stops working indefinitely until the board resets. Consider this sample code.
Code: Select all
#include <ESP32Servo.h>
#define IN1 25
#define IN2 26
#define IN3 27
#define IN4 14
#define ENA 12 //Right Motor Speed
#define ENB 13 //Left Motor Speed
int speedA = 0;
int speedB = 0;
Servo myServo; // Create a servo object
void setup() {
Serial.begin(115200);
myServo.attach(32); // Attach the servo on pin 32
Serial.println("Servo attached to pin 32");
}
void loop() {
for (int pos = 0; pos <= 60; pos++) { // Move the servo from 0 to 180 degrees
myServo.write(pos); // Tell servo to go to position in variable 'pos'
delay(15); // Wait 15 ms for the servo to reach the position
}
for (int pos = 60; pos >= 0; pos--) { // Move the servo back from 180 to 0 degrees
myServo.write(pos); // Tell servo to go to position in variable 'pos'
delay(15); // Wait 15 ms for the servo to reach the position
}
analogWrite(ENA, speedA);
analogWrite(ENB, speedB);
delay(100);
}
Servo does move again and again indefinitely, as expected, without issues when I comment out the analogWrite(); lines.
Questions
- What are the possible causes of this problem?
How to make both the motor driver and the servo work at the same time. At least, what are the things I could try?