ESP32 with Brushelss motor | BLDC

Created At: 2025-04-26 11:22:10 Updated At: 2025-04-26 11:45:01

We love ESP32 and it would be great if we can really rotate a brushless motor or BLDC with it. Here in this case I will use A2212/13T 1000KV motor. It's a pretty powerful motor if you power it with Li-PO 2S or 3S battery.

We will also use 30A ESC that can deliver30 amps continous current flow to the motor.

Since we are just running one motor, then we will use RX2 as PWM pin. We will use RX2 with the yellow wire of ESC(electric speed controller).

Here is the code for ESP32 with brushless motor.  This code also enables you to start, stop and increase the PWM with the keyboard buttons (s, r, +). If you use press s, the motor will stop, if you press r, the motor will rotate, if you press + button PWM will increase.

At the same make sure GND of ESP 32(next to 3.3v) and ESC(brown wire) are connected to common point.

// Motor A Pins
#define AIN1 27
#define AIN2 26
#define PWMA 25
#define STBY 5

// PWM Settings
#define PWM_CHANNEL_A 0
const int pwmFreq = 1000;
const int pwmResolution = 10;
const int minPWM = 0;
const int maxPWM = 1023;

// Function prototypes (corrected)
void driveMotorA(bool dir1, bool dir2, int speed);
void stopMotorA();

int pwmSpeed = 600; // Default startup speed

void setup() {
Serial.begin(115200);

pinMode(AIN1, OUTPUT);
pinMode(AIN2, OUTPUT);
pinMode(STBY, OUTPUT);
digitalWrite(STBY, HIGH); // Enable motor driver

ledcSetup(PWM_CHANNEL_A, pwmFreq, pwmResolution);
ledcAttachPin(PWMA, PWM_CHANNEL_A);

// Auto-run motor on startup
driveMotorA(HIGH, LOW, pwmSpeed); // Forward direction
Serial.println("Motor A Control Ready");
Serial.print("Initial Speed: "); Serial.println(pwmSpeed);
Serial.println("Use + / - to change speed, s to stop");
}

void stopMotorA() {
ledcWrite(PWM_CHANNEL_A, 0);
digitalWrite(AIN1, LOW);
digitalWrite(AIN2, LOW);
}

void driveMotorA(bool dir1, bool dir2, int speed) {
speed = constrain(speed, minPWM, maxPWM);
digitalWrite(AIN1, dir1);
digitalWrite(AIN2, dir2);
ledcWrite(PWM_CHANNEL_A, speed);
}

void loop() {
if (Serial.available()) {
char c = Serial.read();

if (c == '+') {
pwmSpeed = min(pwmSpeed + 50, maxPWM);
Serial.print("Speed: "); Serial.println(pwmSpeed);
driveMotorA(HIGH, LOW, pwmSpeed);
}
else if (c == '-') {
pwmSpeed = max(pwmSpeed - 50, minPWM);
Serial.print("Speed: "); Serial.println(pwmSpeed);
driveMotorA(HIGH, LOW, pwmSpeed);
}
else if (c == 's') {
stopMotorA();
Serial.println("Motor stopped");
}
else if (c == 'r') {
driveMotorA(HIGH, LOW, pwmSpeed);
Serial.println("Motor resumed");
}
}
}

Comment

Add Reviews

Latest Posts

Subscribe our newsletter