ESP32-使用有刷直流电机笔记

基于ESP-IDF4.1

 1 /*
 2  * 刷直流电动机控制示例,代码通过L298电机芯片测试
 3 */
 4 
 5 #include <stdio.h>
 6 
 7 #include "freertos/FreeRTOS.h"
 8 #include "freertos/task.h"
 9 #include "esp_attr.h"
10 
11 #include "driver/mcpwm.h"
12 #include "soc/mcpwm_periph.h"
13 
14 #define GPIO_PWM0A_OUT 15   //设置 GPIO 15 作为 PWM0A
15 #define GPIO_PWM0B_OUT 16   //设置 GPIO 16 作为 PWM0B
16 
17 static void mcpwm_example_gpio_initialize(void)
18 {
19     printf("initializing mcpwm gpio...\n");
20     mcpwm_gpio_init(MCPWM_UNIT_0, MCPWM0A, GPIO_PWM0A_OUT);
21     mcpwm_gpio_init(MCPWM_UNIT_0, MCPWM0B, GPIO_PWM0B_OUT);
22 }
23 
24 /**
25  * @brief 电机向前移动
26  */
27 static void brushed_motor_forward(mcpwm_unit_t mcpwm_num, mcpwm_timer_t timer_num , float duty_cycle)
28 {
29     mcpwm_set_signal_low(mcpwm_num, timer_num, MCPWM_OPR_B);
30     mcpwm_set_duty(mcpwm_num, timer_num, MCPWM_OPR_A, duty_cycle);
31     mcpwm_set_duty_type(mcpwm_num, timer_num, MCPWM_OPR_A, MCPWM_DUTY_MODE_0); 
32 }
33 
34 /**
35  * @brief 电机向后移动
36  */
37 static void brushed_motor_backward(mcpwm_unit_t mcpwm_num, mcpwm_timer_t timer_num , float duty_cycle)
38 {
39     mcpwm_set_signal_low(mcpwm_num, timer_num, MCPWM_OPR_A);
40     mcpwm_set_duty(mcpwm_num, timer_num, MCPWM_OPR_B, duty_cycle);
41     mcpwm_set_duty_type(mcpwm_num, timer_num, MCPWM_OPR_B, MCPWM_DUTY_MODE_0); 
42 }
43 
44 /**
45  * @brief 电机停止
46  */
47 static void brushed_motor_stop(mcpwm_unit_t mcpwm_num, mcpwm_timer_t timer_num)
48 {
49     mcpwm_set_signal_low(mcpwm_num, timer_num, MCPWM_OPR_A);
50     mcpwm_set_signal_low(mcpwm_num, timer_num, MCPWM_OPR_B);
51 }
52 
53 /**
54  * @brief 为有刷直流电机配置MCPWM
55  */
56 static void mcpwm_example_brushed_motor_control(void *arg)
57 {
58     //1. mcpwm gpio 初始化
59     mcpwm_example_gpio_initialize();
60 
61     //2. 初始化 mcpwm 配置
62     printf("Configuring Initial Parameters of mcpwm...\n");
63     mcpwm_config_t pwm_config;
64     pwm_config.frequency = 1000;    //频率 = 500Hz,
65     pwm_config.cmpr_a = 0;    // PWMxA占空比 = 0
66     pwm_config.cmpr_b = 0;    // PWMxb占空比 = 0
67     pwm_config.counter_mode = MCPWM_UP_COUNTER;
68     pwm_config.duty_mode = MCPWM_DUTY_MODE_0;
69     mcpwm_init(MCPWM_UNIT_0, MCPWM_TIMER_0, &pwm_config);
70     while (1) {
71         brushed_motor_forward(MCPWM_UNIT_0, MCPWM_TIMER_0, 50.0);
72         vTaskDelay(2000 / portTICK_RATE_MS);
73         brushed_motor_backward(MCPWM_UNIT_0, MCPWM_TIMER_0, 30.0);
74         vTaskDelay(2000 / portTICK_RATE_MS);
75         brushed_motor_stop(MCPWM_UNIT_0, MCPWM_TIMER_0);
76         vTaskDelay(2000 / portTICK_RATE_MS);
77     }
78 }
79 
80 void app_main(void)
81 {
82     printf("Testing brushed motor...\n");
83     xTaskCreate(mcpwm_example_brushed_motor_control, "mcpwm_examlpe_brushed_motor_control", 4096, NULL, 5, NULL);
84 }

 

原文:https://gitee.com/EspressifSystems/esp-idf/tree/master/examples/peripherals/mcpwm/mcpwm_brushed_dc_control

posted @ 2020-11-13 21:33  kerwin cui  阅读(1949)  评论(0编辑  收藏  举报