一、电机用的PWM——MCPWM
#include <stdio.h>
#include "string.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "esp_attr.h"
#include "soc/rtc.h"
#include "driver/mcpwm.h"
#include "soc/mcpwm_reg.h"
#include "soc/mcpwm_struct.h"
#define GPIO_PWM0A_OUT 19 //Set GPIO 19 as PWM0A
#define GPIO_PWM0B_OUT 18 //Set GPIO 18 as PWM0B
void app_main()
{
mcpwm_pin_config_t pin_config = {
.mcpwm0a_out_num = GPIO_PWM0A_OUT,
.mcpwm0b_out_num = GPIO_PWM0B_OUT
};
mcpwm_set_pin(MCPWM_UNIT_0, &pin_config);
mcpwm_config_t pwm_config;
pwm_config.frequency = 1000; //frequency = 1000Hz
pwm_config.cmpr_a = 60.0; //duty cycle of PWMxA = 60.0%
pwm_config.cmpr_b = 50.0; //duty cycle of PWMxb = 50.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
}
二、LED调光用的PWM——LEDC
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/ledc.h"
#include "esp_err.h"
#define GPIO_LED 2
void app_main()
{
ledc_timer_config_t ledc_timer = {
.duty_resolution = LEDC_TIMER_13_BIT, // resolution of PWM duty
.freq_hz = 5000, // frequency of PWM signal
.speed_mode = LEDC_HIGH_SPEED_MODE, // timer mode
.timer_num = LEDC_TIMER_0 // timer index
};
// Set configuration of timer0 for high speed channels
ledc_timer_config(&ledc_timer);
ledc_channel_config_t ledc_channel[1] =
{
{
.channel =LEDC_CHANNEL_0,
.duty = 0,
.gpio_num = GPIO_LED,
.speed_mode =LEDC_HIGH_SPEED_MODE,
.timer_sel = LEDC_TIMER_0
}
};
int ch;
for (ch = 0; ch < 1; ch++) {
ledc_channel_config(&ledc_channel[ch]);
}
// Initialize fade service.
ledc_fade_func_install(0);
while (1){
for (ch = 0; ch < 1; ch++) {
ledc_set_fade_with_time(ledc_channel[ch].speed_mode,ledc_channel[ch].channel,8000,3000);
ledc_fade_start(ledc_channel[ch].speed_mode,ledc_channel[ch].channel, LEDC_FADE_NO_WAIT);
}
vTaskDelay(3000/portTICK_PERIOD_MS);
for (ch = 0; ch < 1; ch++) {
ledc_set_fade_with_time(ledc_channel[ch].speed_mode,ledc_channel[ch].channel,2000,3000);
ledc_fade_start(ledc_channel[ch].speed_mode,ledc_channel[ch].channel, LEDC_FADE_NO_WAIT);
}
vTaskDelay(3000/portTICK_PERIOD_MS);
}
}