Skip to content

Commit a7bd6c9

Browse files
authored
Fixes analogWrite (#8137)
* Fixes analogWrite * sets cnt_channel index * fixes TAB alligment
1 parent 85d179c commit a7bd6c9

File tree

1 file changed

+22
-16
lines changed

1 file changed

+22
-16
lines changed

cores/esp32/esp32-hal-ledc.c

+22-16
Original file line numberDiff line numberDiff line change
@@ -215,26 +215,32 @@ static int cnt_channel = LEDC_CHANNELS;
215215
static uint8_t analog_resolution = 8;
216216
static int analog_frequency = 1000;
217217
void analogWrite(uint8_t pin, int value) {
218-
// Use ledc hardware for internal pins
219-
if (pin < SOC_GPIO_PIN_COUNT) {
220-
if (pin_to_channel[pin] == 0) {
221-
if (!cnt_channel) {
222-
log_e("No more analogWrite channels available! You can have maximum %u", LEDC_CHANNELS);
223-
return;
224-
}
225-
if(ledcSetup(cnt_channel - 1, analog_frequency, analog_resolution) == 0){
226-
log_e("analogWrite setup failed (freq = %u, resolution = %u). Try setting different resolution or frequency");
227-
return;
228-
}
229-
ledcAttachPin(pin, cnt_channel - 1);
230-
pin_to_channel[pin] = cnt_channel--;
218+
// Use ledc hardware for internal pins
219+
if (pin < SOC_GPIO_PIN_COUNT) {
220+
int8_t channel = -1;
221+
if (pin_to_channel[pin] == 0) {
222+
if (!cnt_channel) {
223+
log_e("No more analogWrite channels available! You can have maximum %u", LEDC_CHANNELS);
224+
return;
225+
}
226+
cnt_channel--;
227+
channel = cnt_channel;
228+
} else {
229+
channel = analogGetChannel(pin);
230+
}
231+
log_v("GPIO %d - Using Channel %d, Value = %d", pin, channel, value);
232+
if(ledcSetup(channel, analog_frequency, analog_resolution) == 0){
233+
log_e("analogWrite setup failed (freq = %u, resolution = %u). Try setting different resolution or frequency");
234+
return;
235+
}
236+
ledcAttachPin(pin, channel);
237+
pin_to_channel[pin] = channel;
238+
ledcWrite(channel, value);
231239
}
232-
ledcWrite(pin_to_channel[pin] - 1, value);
233-
}
234240
}
235241

236242
int8_t analogGetChannel(uint8_t pin) {
237-
return pin_to_channel[pin] - 1;
243+
return pin_to_channel[pin];
238244
}
239245

240246
void analogWriteFrequency(uint32_t freq) {

0 commit comments

Comments
 (0)