#include <math.h> // Include for round() function
// --- Configuration Constants ---
const int pwmPin = 13;
const int frequency = 5000; // PWM frequency in Hz
const uint8_t resolution = 8; // Use 8-bit resolution (0-255 duty cycle range)
// *** New Configuration: Duty Cycle as Percentage ***
const float fixedDutyCyclePercent = 75.0; // Desired fixed duty cycle (0.0 to100.0)
// --- Calculated Values ---
// Calculate the maximum raw duty cycle value based on the resolution
// (1 << N) is 2^N. Max value is 2^N - 1.
const uint32_t maxDutyCycle = (1 << resolution) - 1; // For 8-bit, this is 255
// --- Helper Function ---
// Converts a percentage (0-100) to the raw duty cycle value for the configuredresolution
uint32_t percentageToDuty(float percentage) {
// Clamp percentage to the valid range 0.0 to 100.0
if (percentage < 0.0) {
percentage = 0.0;
} else if (percentage > 100.0) {
percentage = 100.0;
}
// Calculate the raw duty cycle value
// (percentage / 100.0) gives the fraction (0.0 to 1.0)
// Multiply by the maximum possible duty cycle value for the chosen resolution
// Use round() for the nearest integer value
return (uint32_t)round((percentage / 100.0) * maxDutyCycle);
}
// ========================== SETUP ==========================
void setup() {
Serial.begin(115200);
Serial.println("ESP32 Fixed PWM (Percentage Input) Example (Pin-Based API)");
// 1. Configure and attach the PWM pin using LEDC
ledcAttach(pwmPin, frequency, resolution);
Serial.printf("Attached PWM to GPIO %d\n", pwmPin);
Serial.printf("Frequency: %d Hz, Resolution: %d bits (Max Duty Value: %u)\n",
frequency, resolution, maxDutyCycle);
// 2. Convert the desired percentage to the raw duty cycle value
uint32_t calculatedDutyValue = percentageToDuty(fixedDutyCyclePercent);
Serial.printf("Requested Duty Cycle: %.2f %%\n", fixedDutyCyclePercent);
Serial.printf("Calculated Raw Duty Value: %u\n", calculatedDutyValue);
// 3. Set the fixed PWM duty cycle using ledcWrite with the PIN number
// and the CALCULATED duty value
ledcWrite(pwmPin, calculatedDutyValue); // Using pwmPin and calculated value
Serial.printf("Set fixed duty cycle %u on pin %d\n", calculatedDutyValue,
pwmPin);
Serial.println("PWM signal is now active.");
}
// ========================== LOOP ==========================
void loop() {
// PWM is handled by hardware. Nothing needed here for fixed output.
delay(1000);
}