esp32 pwm
扫描二维码
随时随地手机看文章
手上有个42步进电机,结合ESP32开发板搞腾一下,让步进电机转起来。
电机驱动芯片在小板上,啥型号就不知道了,芯片的pin图:
ESP32上有针对电机使用的pwm,在数据手册上有说明:
下面看下具体使用。开发环境自行补脑,利用esp-idf\examples\peripherals\mcpwm 目录下有针对四种类型的电机pwm案例,这次使用的是两相四线步进电机,我在mcpwm_servo_control下进行修改的。
代码:
/* servo motor control example
This example code is in the Public Domain (or CC0 licensed, at your option.)
Unless required by applicable law or agreed to in writing, this
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied.
*/
#include
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_attr.h"
#include "freertos/queue.h"
#include "driver/gpio.h"
#include "driver/mcpwm.h"
#include "soc/mcpwm_reg.h"
#include "soc/mcpwm_struct.h"
//You can get these value from the datasheet of servo you use, in general pulse width varies between 1000 to 2000 mocrosecond
#define SERVO_MIN_PULSEWIDTH 1000 //Minimum pulse width in microsecond
#define SERVO_MAX_PULSEWIDTH 2000 //Maximum pulse width in microsecond
#define SERVO_MAX_DEGREE 90 //Maximum angle in degree upto which servo can rotate
static void mcpwm_example_gpio_initialize()
{
printf("initializing mcpwm servo control gpio......\n");
mcpwm_gpio_init(MCPWM_UNIT_0, MCPWM0A, 15);
mcpwm_gpio_init(MCPWM_UNIT_1, MCPWM1A, 16);
}
/**
* @brief Configure MCPWM module
*/
void mcpwm_example_servo_control(void *arg)
{
//1. mcpwm gpio initialization
mcpwm_example_gpio_initialize();
//2. initial mcpwm configuration
printf("Configuring Initial Parameters of mcpwm......\n");
mcpwm_config_t pwm_config;
pwm_config.frequency = 100; //frequency = 50Hz, i.e. for every servo motor time period should be 20ms
pwm_config.cmpr_a = 50.0; //duty cycle of PWMxA = 0
pwm_config.cmpr_b = 50.0; //duty cycle of PWMxb = 0
pwm_config.counter_mode = MCPWM_UP_COUNTER;
pwm_config.duty_mode = MCPWM_DUTY_MODE_0;
mcpwm_init(MCPWM_UNIT_0, MCPWM_TIMER_0, &pwm_config); //Configure PWM0A & PWM0B with above settings
vTaskDelay(5000);
pwm_config.duty_mode = MCPWM_DUTY_MODE_1;
mcpwm_init(MCPWM_UNIT_1,MCPWM_TIMER_1, &pwm_config); //Configure PWM0A & PWM0B with above settings
while (1)
{
}
}
void app_main()
{
printf("intializing test signal...\n");
gpio_config_t gp;
gp.intr_type = GPIO_INTR_DISABLE;
gp.mode = GPIO_MODE_OUTPUT;
gp.pin_bit_mask = GPIO_SEL_12;
gpio_config(&gp);
gpio_set_level(GPIO_NUM_12, 1); //Set high
printf("Testing servo motor.......\n");
xTaskCreate(mcpwm_example_servo_control, "mcpwm_example_servo_control", 4096, NULL, 5, NULL);
}