@@ -221,7 +221,7 @@ PinStatus digitalRead(pin_size_t pinNumber) {
221221static struct pin_timer {
222222 struct k_timer timer;
223223 uint32_t count;
224- pin_size_t pin;
224+ pin_size_t pin{ pin_size_t (- 1 )} ;
225225 bool infinity;
226226} arduino_pin_timers[MAX_TONE_PINS];
227227
@@ -232,6 +232,7 @@ void tone_expiry_cb(struct k_timer *timer) {
232232 if (pt->count == 0 ) {
233233 k_timer_stop (timer);
234234 gpio_pin_set_dt (spec, 0 );
235+ pt->pin = pin_size_t (-1 );
235236 } else {
236237 gpio_pin_toggle_dt (spec);
237238 if (!pt->infinity ) {
@@ -243,17 +244,24 @@ void tone_expiry_cb(struct k_timer *timer) {
243244void tone (pin_size_t pinNumber, unsigned int frequency,
244245 unsigned long duration) {
245246 const struct gpio_dt_spec *spec = &arduino_pins[pinNumber];
247+ size_t timerIndex = -1 ;
246248 struct k_timer *timer;
247249 k_timeout_t timeout;
248250
249- if (pinNumber >= MAX_TONE_PINS) {
251+ for (size_t i = 0 ; i < ARRAY_SIZE (arduino_pin_timers); i++) {
252+ if (arduino_pin_timers[i].pin == pin_size_t (-1 )) {
253+ timerIndex = i;
254+ }
255+ }
256+
257+ if (timerIndex == size_t (-1 )) {
250258 return ;
251259 }
252260
253- timer = &arduino_pin_timers[pinNumber ].timer ;
261+ timer = &arduino_pin_timers[timerIndex ].timer ;
254262
255263 pinMode (pinNumber, OUTPUT);
256- k_timer_stop (&arduino_pin_timers[pinNumber ].timer );
264+ k_timer_stop (&arduino_pin_timers[timerIndex ].timer );
257265
258266 if (frequency == 0 ) {
259267 gpio_pin_set_dt (spec, 0 );
@@ -265,10 +273,10 @@ void tone(pin_size_t pinNumber, unsigned int frequency,
265273 timeout.ticks = 1 ;
266274 }
267275
268- arduino_pin_timers[pinNumber ].infinity = (duration == 0 );
269- arduino_pin_timers[pinNumber ].count = (uint64_t )duration * frequency *
276+ arduino_pin_timers[timerIndex ].infinity = (duration == 0 );
277+ arduino_pin_timers[timerIndex ].count = (uint64_t )duration * frequency *
270278 (MSEC_PER_SEC / TOGGLES_PER_CYCLE);
271- arduino_pin_timers[pinNumber ].pin = pinNumber;
279+ arduino_pin_timers[timerIndex ].pin = pinNumber;
272280 k_timer_init (timer, tone_expiry_cb, NULL );
273281
274282 gpio_pin_set_dt (spec, 0 );
@@ -277,9 +285,21 @@ void tone(pin_size_t pinNumber, unsigned int frequency,
277285
278286void noTone (pin_size_t pinNumber) {
279287 const struct gpio_dt_spec *spec = &arduino_pins[pinNumber];
288+ uint32_t timerIndex = -1 ;
289+
290+ for (size_t i = 0 ; i < ARRAY_SIZE (arduino_pin_timers); i++) {
291+ if (arduino_pin_timers[i].pin == pinNumber) {
292+ timerIndex = i;
293+ }
294+ }
295+
296+ if (timerIndex == size_t (-1 )) {
297+ return ;
298+ }
280299
281- k_timer_stop (&arduino_pin_timers[pinNumber ].timer );
300+ k_timer_stop (&arduino_pin_timers[timerIndex ].timer );
282301 gpio_pin_set_dt (spec, 0 );
302+ arduino_pin_timers[timerIndex].pin = pin_size_t (-1 );
283303}
284304
285305void delay (unsigned long ms) {
0 commit comments