Skip to content

Instantly share code, notes, and snippets.

@Steve-Tech
Created June 22, 2022 01:23
Show Gist options
  • Save Steve-Tech/277e32318ca6bef1250849129fd2bbd2 to your computer and use it in GitHub Desktop.
Save Steve-Tech/277e32318ca6bef1250849129fd2bbd2 to your computer and use it in GitHub Desktop.
ESP32 MCPWM Timer Sync Offset
/*
* ESP32 MCPWM Timer Sync Offset
* by Steve-Tech
* Creates an output like
* _ _
* TIMER0: | |___| |___|; or 10001000
* _ _ | | | |
* TIMER1: ___| |___| |_; or 00100010
*
* Sources:
* - https://docs.espressif.com/projects/esp-idf/en/v4.4.1/esp32/api-reference/peripherals/mcpwm.html
* - https://github.com/espressif/esp-idf/blob/v4.4.1/examples/peripherals/mcpwm/mcpwm_sync_example/main/mcpwm_sync_example.c
*/
#include "driver/mcpwm.h"
#define MCPWM_UNIT MCPWM_UNIT_0 // Use Unit 0, there are 2 units on an ESP32 - 0 & 1
#define TIMER0_OUTPUT 16 // Output TIMER0 on GPIO16
#define TIMER1_OUTPUT 17 // Output TIMER1 on GPIO17
//#define TIMER2_OUTPUT 18 // There is a TIMER2, but I haven't used it
void setup() {
// Configure PWM
mcpwm_config_t pwm_config = {
.frequency = 1000, // Frequency 1000Hz
.cmpr_a = 25, // 25% duty cycle
.cmpr_b = 0,
.duty_mode = MCPWM_DUTY_MODE_0,
.counter_mode = MCPWM_UP_COUNTER,
};
// Initialise PWM
mcpwm_init(MCPWM_UNIT, MCPWM_TIMER_0, &pwm_config);
mcpwm_init(MCPWM_UNIT, MCPWM_TIMER_1, &pwm_config);
// Configure PWM Sync
mcpwm_sync_config_t sync_conf = {
.sync_sig = MCPWM_SELECT_TIMER0_SYNC, // Sync Signal Source = TIMER0
.timer_val = 500, // Set timer to 50.0%, delaying it 50.0%
//.timer_val = 800, // Set timer to 80.0%, delaying it 20.0% - See example linked above (line 138 & 140)
.count_direction = MCPWM_TIMER_DIRECTION_UP,
};
mcpwm_set_timer_sync_output(MCPWM_UNIT, MCPWM_TIMER_0, MCPWM_SWSYNC_SOURCE_TEZ); // TIMER0: Send Sync Signal on counting to 0
mcpwm_sync_configure(MCPWM_UNIT, MCPWM_TIMER_1, &sync_conf); // TIMER1: Configure with sync_conf
// Enable GPIO Output
mcpwm_gpio_init(MCPWM_UNIT, MCPWM0A, TIMER0_OUTPUT);
mcpwm_gpio_init(MCPWM_UNIT, MCPWM1A, TIMER1_OUTPUT);
}
void loop() {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment