#include "driver/ledc.h"
#include "esp_timer.h"
// Constants
const int sinPWM[] = {
0, 16, 32, 48, 63, 79, 94, 109, 123, 137,
150, 163, 175, 186, 196, 206, 215, 223, 231, 237,
243, 247, 250, 253, 254, 255, 254, 253, 250, 247,
243, 237, 231, 223, 215, 206, 196, 186, 175, 163,
150, 137, 123, 109, 94, 79, 63, 48, 32, 16, 0
};
const int PWM_FREQ = 5000;
const int PWM_RESOLUTION = 8; // 8-bit resolution, values between 0 and 255
// Calculate timer interval for 50Hz (20ms period), assuming sinPWM array has 312 values per cycle
const int TIMER_INTERVAL_US = (10 * 1000) / 50; // Timer interval in microseconds
// Variables
volatile int i = 0, j = 0, k = 0;
volatile bool flagA = false, flagB = false, flagC = false, flagD = false, flagE = false;
// Timer handle
esp_timer_handle_t timer;
// Timer callback function
void timer_callback(void* arg) {
static int x = 0, y = 0, z = 0;
if (i > 50) { i = 0; flagA = !flagA; }
x = sinPWM[i++];
if (!flagA) { ledcWrite(2, x); ledcWrite(4, 0); }
else { ledcWrite(2, 0); ledcWrite(4, x); }
if ((i >= 33) || flagB) {
flagB = true;
if (j > 50) { j = 0; flagC = !flagC; }
y = sinPWM[j++];
if (!flagC) { ledcWrite(5, y); ledcWrite(12, 0); }
else { ledcWrite(5, 0); ledcWrite(12, y); }
}
if ((j >= 33) || flagD) {
flagD = true;
if (k > 50) { k = 0; flagE = !flagE; }
z = sinPWM[k++];
if (!flagE) { ledcWrite(13, z); ledcWrite(14, 0); }
else { ledcWrite(13, 0); ledcWrite(14, z); }
}
}
void setupLEDC(int channel, int freq, int resolution, int pin) {
ledcAttach(pin, freq, resolution);
}
void setup() {
// Set up LEDC (PWM) channels
setupLEDC(2, PWM_FREQ, PWM_RESOLUTION, 2);
setupLEDC(4, PWM_FREQ, PWM_RESOLUTION, 4);
setupLEDC(5, PWM_FREQ, PWM_RESOLUTION, 5);
setupLEDC(12, PWM_FREQ, PWM_RESOLUTION, 12);
setupLEDC(13, PWM_FREQ, PWM_RESOLUTION, 13);
setupLEDC(14, PWM_FREQ, PWM_RESOLUTION, 14);
// Create and start timer
const esp_timer_create_args_t timer_args = {
.callback = &timer_callback,
.name = "PWM Timer"
};
esp_timer_create(&timer_args, &timer);
esp_timer_start_periodic(timer, TIMER_INTERVAL_US); // Calculate appropriate timer interval
}
void loop() {
// Empty loop
}