Skip to content

Commit 4fdcc6e

Browse files
Only init PWM on requested pin (#926)
Avoid glitches on other pins, fix #919
1 parent b82336c commit 4fdcc6e

File tree

1 file changed

+6
-8
lines changed

1 file changed

+6
-8
lines changed

cores/rp2040/wiring_analog.cpp

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828

2929
static uint32_t analogScale = 255;
3030
static uint32_t analogFreq = 1000;
31-
static bool pwmInitted = false;
31+
static uint32_t pwmInitted = 0;
3232
static bool adcInitted = false;
3333
static uint16_t analogWritePseudoScale = 1;
3434
static uint16_t analogWriteSlowScale = 1;
@@ -48,7 +48,7 @@ extern "C" void analogWriteFreq(uint32_t freq) {
4848
} else {
4949
analogFreq = freq;
5050
}
51-
pwmInitted = false;
51+
pwmInitted = 0;
5252
}
5353

5454
extern "C" void analogWriteRange(uint32_t range) {
@@ -57,7 +57,7 @@ extern "C" void analogWriteRange(uint32_t range) {
5757
}
5858
if ((range >= 3) && (range <= 65535)) {
5959
analogScale = range;
60-
pwmInitted = false;
60+
pwmInitted = 0;
6161
} else {
6262
DEBUGCORE("ERROR: analogWriteRange out of range (%d)\n", range);
6363
}
@@ -78,7 +78,7 @@ extern "C" void analogWrite(pin_size_t pin, int val) {
7878
DEBUGCORE("ERROR: Illegal analogWrite pin (%d)\n", pin);
7979
return;
8080
}
81-
if (!pwmInitted) {
81+
if (!(pwmInitted & (1 << pin))) {
8282
// For low frequencies, we need to scale the output max value up to achieve lower periods
8383
analogWritePseudoScale = 1;
8484
while (((clock_get_hz(clk_sys) / ((float)analogScale * analogFreq)) > 255.0) && (analogScale < 32678)) {
@@ -96,10 +96,8 @@ extern "C" void analogWrite(pin_size_t pin, int val) {
9696
pwm_config c = pwm_get_default_config();
9797
pwm_config_set_clkdiv(&c, clock_get_hz(clk_sys) / ((float)analogScale * analogFreq));
9898
pwm_config_set_wrap(&c, analogScale - 1);
99-
for (int i = 0; i < 30; i++) {
100-
pwm_init(pwm_gpio_to_slice_num(i), &c, true);
101-
}
102-
pwmInitted = true;
99+
pwm_init(pwm_gpio_to_slice_num(pin), &c, true);
100+
pwmInitted |= 1 << pin;
103101
}
104102

105103
val <<= analogWritePseudoScale;

0 commit comments

Comments
 (0)