I'm looking for active maintainers for this project as I no longer have the time to support it. Please get in touch if you're interested
This library provides an analogWrite function polyfill for ESP32 Arduino framework by wrapping the ledc library.
Licensed under the MIT license.
The library will do all the timer setup and channel selection work behind the scene so you don't have to worry about that.
#include <Arduino.h>
#include <analogWrite.h>
int pin = LED_BUILTIN;
int brightness = 0;
int brightStep = 1;
void setup()
{
}
void loop()
{
brightness += brightStep;
analogWrite(pin, brightness);
if (brightness == 0 || brightness == 255)
{
brightStep = -brightStep;
}
delay(10);
}
Call the analogWrite
function like in standard arduino framework:
analogWrite(LED_BUILTIN, 255); // value range 0-255 so 255 = 100%
You can also set the maximum value as third parameter:
analogWrite(LED_BUILTIN, 255, 1023); // value range 0-1023 so 255 = 25%
The default timer resolution is set to 13 bits in all the 16 channels, if you want to change that, use the analogWriteResolution
function:
analogWriteResolution(10); // set resolution to 10 bits for all pins
analogWriteResolution(LED_BUILTIN, 10); // set resolution to 10 bits for LED pin
The default PWM frequency is set to 5000 Hz in all the 16 channels, if you want to change that, use the analogWriteFrequency
function:
analogWriteFrequency(10000); // set frequency to 10 KHz for all pins
analogWriteFrequency(LED_BUILTIN, 10000); // set frequency to 10 KHz for LED pin
Please note that both timer resolution and PWM frequency should be calculated to get the expected results, if frequency is not set correctly, the output PWM signal wont be as expected, read more about Supported Range of Frequency and Duty Resolution in the official Espressif documentation website.