I want to create two opposite 20khz PWM signal with 5us dead time for driving h-bridge system, and this is my code.
const int ledPin1 = 12; const int ledPin2 = 13; int count = 0 ; int num = 1 ; void setup() { pinMode(ledPin1, OUTPUT); pinMode(ledPin2, OUTPUT); } void loop() { count++; switch(num){ case 1: if(count<=10){ digitalWrite(ledPin1, LOW); digitalWrite(ledPin2, LOW); } else if(count>10){ num=2; } break; case 2: if(count<=60){ digitalWrite(ledPin1, HIGH); digitalWrite(ledPin2, LOW); } else if(count>60){ num=3; } break; case 3: if(count<70){ digitalWrite(ledPin1, LOW); digitalWrite(ledPin2, LOW); } else if(count>70){ num=4; } break; case 4: if(count<=120){ digitalWrite(ledPin1, LOW); digitalWrite(ledPin2, HIGH); } else if(count>120){ num=1; count=0; } break; }}
but when I test with an oscilloscope. I found some delay when ESP-32 run several cycles. Like the fig.
https://drive.google.com/file/d/1QNZ2ZZtjbOvogMMwLYnJ28dYrukNlOvS/view?usp=sharing
the delay make this wave wider then others, that is unacceptable.
How can I avoid this delay or the other way to create the signal with dead time.
hello,
Why not using PWM instead of processor cycles counts…
What is the Processor FOSC value (elementary count = cycle duration)
We can not see your figure !
Hi.
To share a picture, please share a link to google drive, imgur or another server that can host images.
Regards,
Sara
The image cannot be displayed, so I put the url below.I am trying to generate complementary signals with pwm, is there any examples to refer to?
Hi.
As Paulo mentioned, have you tried using the PWM API instead?
https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/ledc.html
Or: https://github.com/JoaoLopesF/ESP32MotorControl
Regards,
Sara
I solved my problem with MCPWM
Use mcpwm_deadtime_enable to generate a 5us dead time. And the signal is very stable.
Thanks for your help
#include "driver/mcpwm.h"
#include "soc/mcpwm_reg.h"
#include "soc/mcpwm_struct.h"
#define MOTO_GPIO1 12
#define MOTO_GPIO2 13
#define MOTOR_MCPWM_UNIT MCPWM_UNIT_0
void setup() {
mcpwm_gpio_init(MOTOR_MCPWM_UNIT, MCPWM0A, MOTO_GPIO1 );
mcpwm_gpio_init(MOTOR_MCPWM_UNIT, MCPWM0B, MOTO_GPIO2 );
#define MOTO_TIMER MCPWM_TIMER_0
mcpwm_config_t pwm_config;
pwm_config.frequency = 20000;
pwm_config.cmpr_a = 0;
pwm_config.cmpr_b = 0;
pwm_config.counter_mode = MCPWM_UP_COUNTER;
pwm_config.duty_mode = MCPWM_DUTY_MODE_0;
mcpwm_deadtime_enable(MOTOR_MCPWM_UNIT,MOTO_TIMER,MCPWM_ACTIVE_HIGH_COMPLIMENT_MODE,50,50);
mcpwm_init(MOTOR_MCPWM_UNIT, MOTO_TIMER, &pwm_config);
}
void loop() {
mcpwm_set_duty(MOTOR_MCPWM_UNIT, MOTO_TIMER, MCPWM_OPR_A,50);
mcpwm_set_duty_type(MOTOR_MCPWM_UNIT, MOTO_TIMER, MCPWM_OPR_A, MCPWM_DUTY_MODE_1);
mcpwm_set_duty(MOTOR_MCPWM_UNIT, MOTO_TIMER, MCPWM_OPR_B,50);
mcpwm_set_duty_type(MOTOR_MCPWM_UNIT, MOTO_TIMER, MCPWM_OPR_B, MCPWM_DUTY_MODE_1);
}