Skip to content
We have moved: pcb.esp32s.com → pcb32.comSame store. Existing accounts, orders and affiliate commission records are unchanged.
Номер заказа: USD
Номер заказа: USD
pcb32.com
Cart 0

Учебное пособие по управлению двигателем постоянного тока на ESP32 | Скорость и направление с помощью модуля драйвера L298N

Embarking on an electronics project that involves movement? Controlling a DC motor is a fundamental skill, and pairing the powerful Микроконтроллер ESP32 with the versatile L298N motor driver module is a perfect combination for the task. This comprehensive tutorial will guide you through the hardware connections and software programming needed to manage both the speed and spinning direction of a DC motor.

Why Use the ESP32 and L298N Driver?

Он ESP32 is a feature-rich, Wi-Fi and Bluetooth-enabled microcontroller that acts as the brain of your operation. However, its GPIO pins cannot supply enough current to drive a motor directly. This is where the L298N driver module comes in.

The L298N is a dual H-bridge motor controller. Think of it as a powerful middleman between your delicate ESP32 and the power-hungry motor. It can:

  • Control Direction: By activating specific switches (transistors) inside its H-bridge circuit, it can reverse the polarity of the voltage applied to the motor, making it spin clockwise or counter-clockwise.

  • Control Speed: Using a technique called Pulse Width Modulation (PWM), it can rapidly switch the motor’s power on and off to simulate variable voltage, effectively changing its speed.

Components You Will Need

Wiring Guide: Connecting the Components

1. Power Connections:

  • Motor Power: Connect the positive terminal of your external battery (+12V on the L298N) and the ground to the (НД) terminal. This powers the motor itself. Важный: Remove the jumper pin from the ENA pin and the 5V Enable jumper if your supply voltage is greater than 12V. This disconnects the onboard 5V regulator.

  • ESP32 Power: Connect the НД of the L298N to the НД of the ESP32. This creates a common ground, which is crucial for the circuit to work correctly.

2. Motor Outputs:

  • Connect your DC motor’s two wires to the OUT1 и OUT2 terminals on the L298N module.

3. Control Pins:

  • Connect the ENA (Enable A) pin on the L298N to GPIO D13 on the ESP32. This pin will control the speed via PWM.

  • Connect the IN1 pin to GPIO D12 и IN2 pin to GPIO D14. These pins will control the motor’s direction.

Programming the ESP32 with Arduino IDE

The code below initializes the control pins and provides functions to run the motor in different directions at various speeds.

// Define the ESP32 GPIO pins connected to the L298N
const int enA = 13; // PWM pin for speed control
const int in1 = 12;
const int in2 = 14;

// PWM properties for ESP32 (LEDC channel, frequency, resolution)
const int pwmChannel = 0;
const int freq = 30000;
const int resolution = 8; // 8-bit resolution (0-255)

void setup() {
// Set the control pins as outputs
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(enA, OUTPUT);

// Configure the ESP32’s LEDC PWM functionality
ledcSetup(pwmChannel, freq, resolution);
ledcAttachPin(enA, pwmChannel);

// Initially, turn the motor off
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
}

void loop() {
// Function calls to demonstrate motor control
clockwiseDirection();
задержка(2000);
stopMotor();
delay(500);
counterClockwiseDirection();
задержка(2000);
stopMotor();
delay(500);
speedRamp();
задержка(2000);
}

void clockwiseDirection() {
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
ledcWrite(pwmChannel, 200); // Set speed to ~200/255
}

void counterClockwiseDirection() {
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
ledcWrite(pwmChannel, 200); // Set speed to ~200/255
}

void stopMotor() {
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
ledcWrite(pwmChannel, 0); // Set speed to 0
}

void speedRamp() {
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
// Gradually increase speed from 0 to max
for (int dutyCycle = 0; dutyCycle <= 255; dutyCycle++) {
ledcWrite(pwmChannel, dutyCycle);
delay(20);
}
// Gradually decrease speed from max to 0
for (int dutyCycle = 255; dutyCycle >= 0; dutyCycle–) {
ledcWrite(pwmChannel, dutyCycle);
delay(20);
}
}

Understanding the Code Logic

  • Direction Control: Setting IN1 = HIGH и IN2 = LOW makes the motor spin in one direction. Reversing these logic levels (IN1 = LOW, IN2 = HIGH) reverses the motor.

  • Speed Control: Он ledcWrite() function generates a PWM signal on the ENA pin. A value of 0 is stop, and 255 is full speed. The speedRamp() function demonstrates how to smoothly change the speed.

Устранение распространенных проблем

  • Motor Doesn’t Spin: Double-check all wiring, especially the common ground between the ESP32 and the L298N. Ensure the external battery is charged.

  • L298N Module Gets Hot: The L298N has a significant voltage drop and can get warm during operation. For high-current motors, consider using a heatsink or a more efficient driver like a TB6612FNG.

  • Jumpy Motor at Low Speed: PWM frequency might be too low. The code uses 30 kHz, which is often better for motor control than the default 490 Hz, as it reduces audible noise.

This setup forms the foundation for countless projects, from simple robots and car kits to automated curtains and conveyor belts. By mastering this, you unlock a world of possibilities for adding motion to your Интернет вещей creations.

======================================

О сайте ESP32S.com

С 2016 года, ESP32S.com Наша компания превратилась в полноценного партнера по экосистеме для вашего развития в сфере Интернета вещей. Расположенная в Шэньчжэне, глобальном центре инноваций в электронике, мы помогли сотням разработчиков и компаний реализовать свои проекты. ESP32Воплощаем идеи в жизнь. Наша команда стремится оказывать исключительную поддержку и предлагать инновационные решения, которые помогут вам достичь ваших целей в области Интернета вещей.
В ESP32S.com, мы осваиваем тонкости разработки ESP32Разработка продукта, основанного на концепции, включает в себя множество этапов, от разработки до вывода на рынок. Именно поэтому мы предлагаем комплексные решения, охватывающие весь жизненный цикл продукта. ESP32Устройства на базе [технологии]. Независимо от того, нужна ли вам помощь в проектировании печатных плат, создании прототипов, производстве или даже маркетинге и доставке, мы вам поможем.

Свяжитесь с нами

Готовы вывести свой IoT-проект на новый уровень? Свяжитесь с ESP32S.com Узнайте больше о наших комплексных решениях уже сегодня! ESP32Устройства на базе [технологии]. Позвольте нам стать вашим надежным партнером в воплощении ваших инновационных идей в жизнь. Свяжитесь с нами прямо сейчас для начала.