@@ -166,14 +166,15 @@ void ledcAttachPin(uint8_t pin, uint8_t chan)
166166 return ;
167167 }
168168 uint8_t group = (chan /8 ), channel = (chan %8 ), timer = ((chan /2 )%4 );
169-
169+ uint32_t duty = ledc_get_duty (group ,channel );
170+
170171 ledc_channel_config_t ledc_channel = {
171172 .speed_mode = group ,
172173 .channel = channel ,
173174 .timer_sel = timer ,
174175 .intr_type = LEDC_INTR_DISABLE ,
175176 .gpio_num = pin ,
176- .duty = 0 ,
177+ .duty = duty ,
177178 .hpoint = 0
178179 };
179180 ledc_channel_config (& ledc_channel );
@@ -211,6 +212,8 @@ uint32_t ledcChangeFrequency(uint8_t chan, uint32_t freq, uint8_t bit_num)
211212
212213static int8_t pin_to_channel [SOC_GPIO_PIN_COUNT ] = { 0 };
213214static int cnt_channel = LEDC_CHANNELS ;
215+ static uint8_t analog_resolution = 8 ;
216+ static int analog_frequency = 1000 ;
214217void analogWrite (uint8_t pin , int value ) {
215218 // Use ledc hardware for internal pins
216219 if (pin < SOC_GPIO_PIN_COUNT ) {
@@ -220,8 +223,8 @@ void analogWrite(uint8_t pin, int value) {
220223 return ;
221224 }
222225 pin_to_channel [pin ] = cnt_channel -- ;
226+ ledcSetup (cnt_channel , analog_frequency , analog_resolution );
223227 ledcAttachPin (pin , cnt_channel );
224- ledcSetup (cnt_channel , 1000 , 8 );
225228 }
226229 ledcWrite (pin_to_channel [pin ] - 1 , value );
227230 }
@@ -230,3 +233,25 @@ void analogWrite(uint8_t pin, int value) {
230233int8_t analogGetChannel (uint8_t pin ) {
231234 return pin_to_channel [pin ] - 1 ;
232235}
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