#include <math.h> // For round()
#include "driver/ledc.h"
// --- Configuration Constants ---
const int pwmPin = 13; // GPIO where LED is connected
const int pwmChannel = 0; // Use PWM channel 0
const int frequency = 5000; // 5 kHz PWM frequency
const uint8_t resolution = 8; // 8-bit resolution (0-255)
// Duty cycle in percentage
const float fixedDutyCyclePercent = 75.0;
// Calculate max duty cycle value
const uint32_t maxDutyCycle = (1 << resolution) - 1;
// Helper: Convert percentage to raw duty cycle
uint32_t percentageToDuty(float percentage) {
if (percentage < 0.0) percentage = 0.0;
if (percentage > 100.0) percentage = 100.0;
return (uint32_t)round((percentage / 100.0) * maxDutyCycle);
}
void setup() {
Serial.begin(115200);
Serial.println("ESP32 Fixed PWM (Using Correct API)");
// Step 1: Configure PWM channel
ledcSetup(pwmChannel, frequency, resolution);
// Step 2: Attach PWM channel to pin
ledcAttachPin(pwmPin, pwmChannel);
// Step 3: Set duty cycle
uint32_t duty = percentageToDuty(fixedDutyCyclePercent);
ledcWrite(pwmChannel, duty);
Serial.printf("PWM setup complete on pin %d with %.1f%% duty cycle\n", pwmPin, fixedDutyCyclePercent);
}
void loop() {
// Nothing needed in loop for fixed output
delay(1000);
}