Skip to content

Commit 1b4f688

Browse files
Ayush1325DhruvaG2000
authored andcommitted
zephyrCommon: Add tone and noTone
- Add implementation of tone and noTone - Use another one-shot timer to stop the first timer. - Silence when frequency = 0 Signed-off-by: Ayush Singh <[email protected]>
1 parent e69c61e commit 1b4f688

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

cores/arduino/zephyrCommon.cpp

+45
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,51 @@ PinStatus digitalRead(pin_size_t pinNumber) {
210210
return (gpio_pin_get_dt(&arduino_pins[pinNumber]) == 1) ? HIGH : LOW;
211211
}
212212

213+
struct k_timer arduino_pin_timers[ARRAY_SIZE(arduino_pins)];
214+
struct k_timer arduino_pin_timers_timeout[ARRAY_SIZE(arduino_pins)];
215+
216+
void tone_expiry_cb(struct k_timer *timer) {
217+
const struct gpio_dt_spec *spec = (gpio_dt_spec*)k_timer_user_data_get(timer);
218+
gpio_pin_toggle_dt(spec);
219+
}
220+
221+
void tone_timeout_cb(struct k_timer *timer) {
222+
pin_size_t pinNumber = (pin_size_t)(uintptr_t)k_timer_user_data_get(timer);
223+
noTone(pinNumber);
224+
}
225+
226+
void tone(pin_size_t pinNumber, unsigned int frequency, unsigned long duration) {
227+
struct k_timer *timer = &arduino_pin_timers[pinNumber];
228+
const struct gpio_dt_spec *spec = &arduino_pins[pinNumber];
229+
k_timeout_t timeout;
230+
231+
pinMode(pinNumber, OUTPUT);
232+
233+
if (frequency == 0) {
234+
gpio_pin_set_dt(spec, 0);
235+
return;
236+
}
237+
238+
timeout = K_NSEC(NSEC_PER_SEC / (2 * frequency));
239+
240+
k_timer_init(timer, tone_expiry_cb, NULL);
241+
k_timer_user_data_set(timer, (void*)spec);
242+
gpio_pin_set_dt(spec, 1);
243+
k_timer_start(timer, timeout, timeout);
244+
245+
if(duration > 0) {
246+
timer = &arduino_pin_timers_timeout[pinNumber];
247+
k_timer_init(timer, tone_timeout_cb, NULL);
248+
k_timer_user_data_set(timer, (void*)(uintptr_t)pinNumber);
249+
k_timer_start(timer, K_MSEC(duration), K_NO_WAIT);
250+
}
251+
}
252+
253+
void noTone(pin_size_t pinNumber) {
254+
k_timer_stop(&arduino_pin_timers[pinNumber]);
255+
gpio_pin_set_dt(&arduino_pins[pinNumber], 0);
256+
}
257+
213258
void delay(unsigned long ms) { k_sleep(K_MSEC(ms)); }
214259

215260
void delayMicroseconds(unsigned int us) { k_sleep(K_USEC(us)); }

0 commit comments

Comments
 (0)