diff --git a/cores/esp32/esp32-hal-ledc.c b/cores/esp32/esp32-hal-ledc.c index 74b6a8cccc1..37ddfaee440 100644 --- a/cores/esp32/esp32-hal-ledc.c +++ b/cores/esp32/esp32-hal-ledc.c @@ -65,10 +65,10 @@ static bool ledcDetachBus(void *bus) { } } pinMatrixOutDetach(handle->pin, false, false); - free(handle); if (!channel_found) { ledc_handle.used_channels &= ~(1UL << handle->channel); } + free(handle); if (ledc_handle.used_channels == 0) { ledc_fade_func_uninstall(); fade_initialized = false; @@ -136,8 +136,8 @@ bool ledcAttachChannel(uint8_t pin, uint32_t freq, uint8_t resolution, uint8_t c //get resolution of selected channel when used if (channel_used) { uint32_t channel_resolution = 0; - log_i("Channel %u frequency: %u, resolution: %u", channel, ledc_get_freq(group, timer), channel_resolution); ledc_ll_get_duty_resolution(LEDC_LL_GET_HW(), group, timer, &channel_resolution); + log_i("Channel %u frequency: %u, resolution: %u", channel, ledc_get_freq(group, timer), channel_resolution); handle->channel_resolution = (uint8_t)channel_resolution; } else { diff --git a/libraries/ESP32/examples/AnalogOut/LEDCSingleChannel/LEDCSingleChannel.ino b/libraries/ESP32/examples/AnalogOut/LEDCSingleChannel/LEDCSingleChannel.ino new file mode 100644 index 00000000000..82e74c07895 --- /dev/null +++ b/libraries/ESP32/examples/AnalogOut/LEDCSingleChannel/LEDCSingleChannel.ino @@ -0,0 +1,50 @@ +/* + LEDC Software Fade on shared channel with multiple pins + + This example shows how to software fade LED + using the ledcWriteChannel function on multiple pins. + This example is useful if you need to control synchronously + multiple LEDs on different pins. + + Code adapted from original Arduino Fade example: + https://www.arduino.cc/en/Tutorial/Fade + + This example code is in the public domain. + */ + +// use 8 bit precision for LEDC timer +#define LEDC_TIMER_8_BIT 8 + +// use 5000 Hz as a LEDC base frequency +#define LEDC_BASE_FREQ 5000 + +// LED pins +#define LED_PIN_1 4 +#define LED_PIN_2 5 + +// LED channel that will be used instead of automatic selection. +#define LEDC_CHANNEL 0 + +int brightness = 0; // how bright the LED is +int fadeAmount = 5; // how many points to fade the LED by + +void setup() { + // Use single LEDC channel 0 for both pins + ledcAttachChannel(LED_PIN_1, LEDC_BASE_FREQ, LEDC_TIMER_8_BIT, LEDC_CHANNEL); + ledcAttachChannel(LED_PIN_2, LEDC_BASE_FREQ, LEDC_TIMER_8_BIT, LEDC_CHANNEL); +} + +void loop() { + // set the brightness on LEDC channel 0 + ledcWriteChannel(LEDC_CHANNEL, brightness); + + // change the brightness for next time through the loop: + brightness = brightness + fadeAmount; + + // reverse the direction of the fading at the ends of the fade: + if (brightness <= 0 || brightness >= 255) { + fadeAmount = -fadeAmount; + } + // wait for 30 milliseconds to see the dimming effect + delay(30); +} \ No newline at end of file