此示例类使用 ESP-IDF 的 LEDC PWM 驱动来控制 DRV8231 电机驱动器(你也可以使用 MCPWM 驱动)来控制 DRV8231 电机驱动器。
头文件 (DRV8231.hpp)
DRV8231.hpp
#pragma once
#include <cstdio>
#include <cstdint>
#include <driver/gpio.h>
#include <driver/ledc.h>
class DRV8231 {
public:
DRV8231(gpio_num_t pwmA, gpio_num_t pwmB, ledc_channel_t channelA, ledc_channel_t channelB);
void Start(uint16_t speed, bool reverse=false);
void Stop();
private:
gpio_num_t pwmA;
gpio_num_t pwmB;
ledc_channel_t channelA;
ledc_channel_t channelB;
};源文件 (DRV8231.cpp)
DRV8231.cpp
#include "DRV8231.hpp"
#include <algorithm>
DRV8231::DRV8231(gpio_num_t pwmA, gpio_num_t pwmB, ledc_channel_t channelA, ledc_channel_t channelB) {
// 存储引脚编号
this->pwmA = pwmA;
this->pwmB = pwmB;
this->channelA = channelA;
this->channelB = channelB;
// 配置 LEDC 定时器以生成 PWM
ledc_timer_config_t ledc_timer = {
.speed_mode = LEDC_LOW_SPEED_MODE,
.duty_resolution = LEDC_TIMER_10_BIT, // 8 位分辨率 (0-255)
.timer_num = LEDC_TIMER_0,
.freq_hz = 20000, // 设置频率为 100kHz
.clk_cfg = LEDC_AUTO_CLK
};
ESP_ERROR_CHECK(ledc_timer_config(&ledc_timer));
// 配置 pwmA 的 LEDC 通道
ledc_channel_config_t ledc_channel_a = {
.gpio_num = pwmA,
.speed_mode = LEDC_LOW_SPEED_MODE,
.channel = channelA,
.intr_type = LEDC_INTR_DISABLE,
.timer_sel = LEDC_TIMER_0,
.duty = 0, // 初始化占空比为 0
.hpoint = 0
};
ESP_ERROR_CHECK(ledc_channel_config(&ledc_channel_a));
// 配置 pwmB 的 LEDC 通道
ledc_channel_config_t ledc_channel_b = {
.gpio_num = pwmB,
.speed_mode = LEDC_LOW_SPEED_MODE,
.channel = channelB,
.intr_type = LEDC_INTR_DISABLE,
.timer_sel = LEDC_TIMER_0,
.duty = 0, // 初始化占空比为 0
.hpoint = 0
};
ESP_ERROR_CHECK(ledc_channel_config(&ledc_channel_b));
}
void DRV8231::Start(uint16_t speed, bool reverse) {
uint16_t duty = std::min(speed, (uint16_t)1023); // 将速度限制在 0-1023 范围内
// 设置方向和占空比
if (reverse) {
ledc_set_duty(LEDC_LOW_SPEED_MODE, channelB, duty);
ledc_update_duty(LEDC_LOW_SPEED_MODE, channelB);
ledc_set_duty(LEDC_LOW_SPEED_MODE, channelA, 1023);
ledc_update_duty(LEDC_LOW_SPEED_MODE, channelA);
} else {
ledc_set_duty(LEDC_LOW_SPEED_MODE, channelA, duty);
ledc_update_duty(LEDC_LOW_SPEED_MODE, channelA);
ledc_set_duty(LEDC_LOW_SPEED_MODE, channelB, 1023); // 100%
ledc_update_duty(LEDC_LOW_SPEED_MODE, channelB);
}
}
void DRV8231::Stop() {
// 将两个通道设置为 100% 占空比(即制动)
ledc_set_duty(LEDC_LOW_SPEED_MODE, channelA, 1023);
ledc_update_duty(LEDC_LOW_SPEED_MODE, channelA);
ledc_set_duty(LEDC_LOW_SPEED_MODE, channelB, 1023);
ledc_update_duty(LEDC_LOW_SPEED_MODE, channelB);
}使用示例
usage_example.cpp
#include "DRV8231.hpp"
DRV8231 motor(GPIO_NUM_7, GPIO_NUM_8, LEDC_CHANNEL_0, LEDC_CHANNEL_1);
extern "C" void app_main() {
while (true) {
// 初始化 DRV8231 驱动
motor.Start(512); // 以半速启动电机
vTaskDelay(pdMS_TO_TICKS(2000)); // 运行 2 秒
motor.Stop(); // 停止电机
}
}