Skip to content

Commit 029471e

Browse files
Drive pin LOW after Tone(period) timeout (#887)
Fixes #886
1 parent 4cc6c36 commit 029471e

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

cores/rp2040/Tone.cpp

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ typedef struct {
2828
pin_size_t pin;
2929
PIO pio;
3030
int sm;
31+
int off;
3132
alarm_id_t alarm;
3233
} Tone;
3334

@@ -38,10 +39,18 @@ auto_init_mutex(_toneMutex);
3839
static PIOProgram _tone2Pgm(&tone2_program);
3940
static std::map<pin_size_t, Tone *> _toneMap;
4041

42+
static inline bool pio_sm_get_enabled(PIO pio, uint sm) {
43+
check_pio_param(pio);
44+
check_sm_param(sm);
45+
return (pio->ctrl & ~(1u << sm)) & (1 << sm);
46+
}
47+
4148
int64_t _stopTonePIO(alarm_id_t id, void *user_data) {
4249
(void) id;
4350
Tone *tone = (Tone *)user_data;
4451
tone->alarm = 0;
52+
digitalWrite(tone->pin, LOW);
53+
pinMode(tone->pin, OUTPUT);
4554
pio_sm_set_enabled(tone->pio, tone->sm, false);
4655
return 0;
4756
}
@@ -72,14 +81,12 @@ void tone(uint8_t pin, unsigned int frequency, unsigned long duration) {
7281
newTone = new Tone();
7382
newTone->pin = pin;
7483
pinMode(pin, OUTPUT);
75-
int off;
76-
if (!_tone2Pgm.prepare(&newTone->pio, &newTone->sm, &off)) {
84+
if (!_tone2Pgm.prepare(&newTone->pio, &newTone->sm, &newTone->off)) {
7785
DEBUGCORE("ERROR: tone unable to start, out of PIO resources\n");
7886
// ERROR, no free slots
7987
delete newTone;
8088
return;
8189
}
82-
tone2_program_init(newTone->pio, newTone->sm, off, pin);
8390
newTone->alarm = 0;
8491
} else {
8592
newTone = entry->second;
@@ -88,6 +95,9 @@ void tone(uint8_t pin, unsigned int frequency, unsigned long duration) {
8895
newTone->alarm = 0;
8996
}
9097
}
98+
if (!pio_sm_get_enabled(newTone->pio, newTone->sm)) {
99+
tone2_program_init(newTone->pio, newTone->sm, newTone->off, pin);
100+
}
91101
pio_sm_clear_fifos(newTone->pio, newTone->sm); // Remove any old updates that haven't yet taken effect
92102
pio_sm_put_blocking(newTone->pio, newTone->sm, RP2040::usToPIOCycles(us));
93103
pio_sm_set_enabled(newTone->pio, newTone->sm, true);

0 commit comments

Comments
 (0)