#include <driver/ledc.h>
#include <math.h>
// Define PWM properties
const int pwmFreq = 390000; // 390kHz PWM frequency
const int pwmResolution = 7; // 7-bit resolution
// Define output pins for H-bridge (connected to MOSFET gates)
const int pwmPinA = 16; // PWM for half-bridge A
const int pwmPinB = 17; // PWM for half-bridge B
// Define enable pins for H-bridge
const int enablePin1 = 18; // Enable pin for H-bridge side 1
const int enablePin2 = 19; // Enable pin for H-bridge side 2
// Define sine wave parameters
const int sineResolution = 100; // Number of points in one sine wave cycle
int sineTable[sineResolution];
// Define pulse timing parameters
const unsigned long pulseDuration = 100; // 100ms
const unsigned long pulseInterval = 1000; // 1s
unsigned long lastPulseTime = 0;
// Define deadband parameters
const int deadband = 5; // Deadband duration in microseconds
void setup() {
// Configure PWM pins as outputs
pinMode(pwmPinA, OUTPUT);
pinMode(pwmPinB, OUTPUT);
// Configure enable pins as outputs
pinMode(enablePin1, OUTPUT);
pinMode(enablePin2, OUTPUT);
// Enable H-bridge initially
digitalWrite(enablePin1, HIGH);
digitalWrite(enablePin2, HIGH);
// Configure and attach PWM pins
ledcAttach(pwmPinA, pwmFreq, pwmResolution);
ledcAttach(pwmPinB, pwmFreq, pwmResolution);
// Generate sine table
for (int i = 0; i < sineResolution; i++) {
sineTable[i] = (int)(sin(i * 2.0 * PI / sineResolution) * ((1 << pwmResolution) - 1) / 2);
}
}
void loop() {
unsigned long currentTime = millis();
// Check if it's time to start a new pulse
if (currentTime - lastPulseTime >= pulseInterval) {
lastPulseTime = currentTime;
}
// Generate a sine pulse if within the pulse duration
if (currentTime - lastPulseTime < pulseDuration) {
static unsigned long lastTime = 0;
static int index = 0;
// Calculate time for one full sine wave cycle at 40kHz
unsigned long cycleTime = 1000 / 40;
// Update index based on elapsed time
if (micros() - lastTime >= cycleTime * 1000 / sineResolution) {
lastTime = micros();
// Set PWM duty cycle based on sine table
int dutyCycle = sineTable[index];
// Implement deadband
digitalWrite(enablePin1, LOW);
digitalWrite(enablePin2, LOW);
delayMicroseconds(deadband);
// Bipolar modulation: activate MOSFETs alternately
if (dutyCycle >= 0) {
ledcWrite(pwmPinA, dutyCycle);
ledcWrite(pwmPinB, 0);
} else {
ledcWrite(pwmPinA, 0);
ledcWrite(pwmPinB, -dutyCycle);
}
// Enable H-bridge after deadband
digitalWrite(enablePin1, HIGH);
digitalWrite(enablePin2, HIGH);
// Update index and reset if it reaches sine resolution
index++;
if (index >= sineResolution) {
index = 0;
}
}
} else {
// Disable PWM output outside the pulse duration
ledcWrite(pwmPinA, 0);
ledcWrite(pwmPinB, 0);
}
}