@@ -166,14 +166,15 @@ void ledcAttachPin(uint8_t pin, uint8_t chan)
166
166
return ;
167
167
}
168
168
uint8_t group = (chan /8 ), channel = (chan %8 ), timer = ((chan /2 )%4 );
169
-
169
+ uint32_t duty = ledc_get_duty (group ,channel );
170
+
170
171
ledc_channel_config_t ledc_channel = {
171
172
.speed_mode = group ,
172
173
.channel = channel ,
173
174
.timer_sel = timer ,
174
175
.intr_type = LEDC_INTR_DISABLE ,
175
176
.gpio_num = pin ,
176
- .duty = 0 ,
177
+ .duty = duty ,
177
178
.hpoint = 0
178
179
};
179
180
ledc_channel_config (& ledc_channel );
@@ -211,6 +212,8 @@ uint32_t ledcChangeFrequency(uint8_t chan, uint32_t freq, uint8_t bit_num)
211
212
212
213
static int8_t pin_to_channel [SOC_GPIO_PIN_COUNT ] = { 0 };
213
214
static int cnt_channel = LEDC_CHANNELS ;
215
+ static uint8_t analog_resolution = 8 ;
216
+ static int analog_frequency = 1000 ;
214
217
void analogWrite (uint8_t pin , int value ) {
215
218
// Use ledc hardware for internal pins
216
219
if (pin < SOC_GPIO_PIN_COUNT ) {
@@ -220,8 +223,8 @@ void analogWrite(uint8_t pin, int value) {
220
223
return ;
221
224
}
222
225
pin_to_channel [pin ] = cnt_channel -- ;
226
+ ledcSetup (cnt_channel , analog_frequency , analog_resolution );
223
227
ledcAttachPin (pin , cnt_channel );
224
- ledcSetup (cnt_channel , 1000 , 8 );
225
228
}
226
229
ledcWrite (pin_to_channel [pin ] - 1 , value );
227
230
}
@@ -230,3 +233,25 @@ void analogWrite(uint8_t pin, int value) {
230
233
int8_t analogGetChannel (uint8_t pin ) {
231
234
return pin_to_channel [pin ] - 1 ;
232
235
}
236
+
237
+ void analogWriteFrequency (uint32_t freq ) {
238
+ if (cnt_channel != LEDC_CHANNELS ) {
239
+ for (int channel = LEDC_CHANNELS - 1 ; channel >= cnt_channel ; channel -- ) {
240
+ ledcChangeFrequency (channel , freq , analog_resolution );
241
+ }
242
+ }
243
+ analog_frequency = freq ;
244
+ }
245
+
246
+ void analogWriteResolution (uint8_t bits ) {
247
+ if (bits > LEDC_MAX_BIT_WIDTH ) {
248
+ log_w ("analogWrite resolution width too big! Setting to maximum %u bits)" , LEDC_MAX_BIT_WIDTH );
249
+ bits = LEDC_MAX_BIT_WIDTH ;
250
+ }
251
+ if (cnt_channel != LEDC_CHANNELS ) {
252
+ for (int channel = LEDC_CHANNELS - 1 ; channel >= cnt_channel ; channel -- ) {
253
+ ledcChangeFrequency (channel , analog_frequency , bits );
254
+ }
255
+ }
256
+ analog_resolution = bits ;
257
+ }
0 commit comments