1. 程式人生 > 實用技巧 >ESP32-使用有刷直流電機筆記

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