Go Down

Topic: I'm having problems controlling a servo and l293d with ESP32 (Read 1 time) previous topic - next topic

charmander123

Hey all,
I'm trying to connect my servo and l293d motor driver to my ESP32 for my bluetooth car.  Currently I have the servo working fine and the l293d works but I can only go at max speed.  My problem with controlling the pwm of both devices is because using multiple PWM channels seems to do something bad. 

If i do ledcAttachPin for the servo and ledcAttachPin for the motor they seem to interfere with eachother and one stops working.  Can someone please help me.  I have attached my test code

Code: [Select]
#include "esp32-hal-ledc.h"

// L293D pins
int motor1Pin1 = 27;
int motor1Pin2 = 26;
int enable1Pin = 14;
 
// Setting PWM properties for L293D
const int freq = 30000;
const int l293dPwmChannel = 0;
const int resolution = 16;
int dutyCycle = 200;

// servo variables
#define COUNT_LOW 1500
#define COUNT_HIGH 6500
#define TIMER_WIDTH 16
#define SERVO_PIN 18
#define SERVO_FREQUENCY 50
const int servoPwmChannel = 1;
 
void setup() {
  // sets the pins as outputs for L293D
  pinMode(motor1Pin1, OUTPUT);
  pinMode(motor1Pin2, OUTPUT);
  pinMode(enable1Pin, OUTPUT);
  
  // enable PWM for L293D Enable pin
  ledcSetup(l293dPwmChannel, freq, resolution);
  ledcAttachPin(enable1Pin, l293dPwmChannel);

  // enable pwm for servo control pin
  ledcSetup(servoPwmChannel, SERVO_FREQUENCY, TIMER_WIDTH); // channel 1, 50 Hz, 16-bit width
  ledcAttachPin(SERVO_PIN, servoPwmChannel);   // GPIO 22 assigned to channel 1
  
  Serial.begin(115200);
}

void moveForward() {
    // Move the DC motor forward at maximum speed
  Serial.println("Moving Forward");
  digitalWrite(motor1Pin1, LOW);
  digitalWrite(motor1Pin2, HIGH);
}

void moveBackward() {
    // Move DC motor backwards at maximum speed
  Serial.println("Moving Backwards");
  digitalWrite(motor1Pin1, HIGH);
  digitalWrite(motor1Pin2, LOW);
}

void stopMotor() {
    // Stop the DC motor
  Serial.println("Motor stopped");
  digitalWrite(motor1Pin1, LOW);
  digitalWrite(motor1Pin2, LOW);
}
void loop() {
  moveForward();
  delay(2000);
 
  stopMotor();
  delay(1000);
 
  moveBackward();
  delay(2000);
 
  stopMotor();
  delay(1000);
 
  // Move DC motor forward with increasing speed
  digitalWrite(motor1Pin1, HIGH);
  digitalWrite(motor1Pin2, LOW);
  while (dutyCycle <= 255){
    ledcWrite(l293dPwmChannel, dutyCycle);  
    Serial.print("Forward with duty cycle: ");
    Serial.println(dutyCycle);
    dutyCycle = dutyCycle + 5;
    delay(500);
  }
  dutyCycle = 200;

  stopMotor();
  delay(1000);
  
  // move the servo
  Serial.println("Operating servo");
  for (int i=COUNT_LOW ; i < COUNT_HIGH ; i=i+100)
   {
      ledcWrite(servoPwmChannel, i);       // sweep servo 1
      delay(50);
   }
  
}

Go Up