Skip to content

Commit 96c184d

Browse files
authored
Add basic analogWrite support based on LEDC (#5861)
1 parent da72bc9 commit 96c184d

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

Diff for: cores/esp32/esp32-hal-ledc.c

+19
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
#include "freertos/task.h"
1818
#include "freertos/semphr.h"
1919
#include "esp32-hal-matrix.h"
20+
#include "soc/soc_caps.h"
2021
#include "soc/ledc_reg.h"
2122
#include "soc/ledc_struct.h"
2223
#include "driver/periph_ctrl.h"
@@ -331,3 +332,21 @@ double ledcChangeFrequency(uint8_t chan, double freq, uint8_t bit_num)
331332
double res_freq = _ledcSetupTimerFreq(chan, freq, bit_num);
332333
return res_freq;
333334
}
335+
336+
static int8_t pin_to_channel[SOC_GPIO_PIN_COUNT] = { 0 };
337+
static int cnt_channel = SOC_LEDC_CHANNEL_NUM;
338+
void analogWrite(uint8_t pin, int value) {
339+
// Use ledc hardware for internal pins
340+
if (pin < SOC_GPIO_PIN_COUNT) {
341+
if (pin_to_channel[pin] == 0) {
342+
if (!cnt_channel) {
343+
log_e("No more analogWrite channels available! You can have maximum %u", SOC_LEDC_CHANNEL_NUM);
344+
return;
345+
}
346+
pin_to_channel[pin] = cnt_channel--;
347+
ledcAttachPin(pin, cnt_channel);
348+
ledcSetup(cnt_channel, 1000, 8);
349+
}
350+
ledcWrite(pin_to_channel[pin] - 1, value);
351+
}
352+
}

Diff for: cores/esp32/esp32-hal.h

+2
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,8 @@ void yield(void);
9090
#include "esp32-hal-psram.h"
9191
#include "esp32-hal-cpu.h"
9292

93+
void analogWrite(uint8_t pin, int value);
94+
9395
//returns chip temperature in Celsius
9496
float temperatureRead();
9597

0 commit comments

Comments
 (0)