From 28ef76cda6dbef258ab51104fc056e08dc83e728 Mon Sep 17 00:00:00 2001 From: Ayush Singh Date: Sat, 8 Jun 2024 16:24:45 +0530 Subject: [PATCH] zephyrCommon: Implement pulseIn - A basic sync implementation - Use ticks for better resolution Signed-off-by: Ayush Singh --- cores/arduino/zephyrCommon.cpp | 43 ++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/cores/arduino/zephyrCommon.cpp b/cores/arduino/zephyrCommon.cpp index 219d3cda..e5c02681 100644 --- a/cores/arduino/zephyrCommon.cpp +++ b/cores/arduino/zephyrCommon.cpp @@ -328,3 +328,46 @@ void detachInterrupt(pin_size_t pinNumber) { setInterruptHandler(pinNumber, nullptr); } + +unsigned long pulseIn(pin_size_t pinNumber, uint8_t state, unsigned long timeout) { + struct k_timer timer; + int64_t start, end, delta = 0; + const struct gpio_dt_spec *spec = &arduino_pins[pinNumber]; + + k_timer_init(&timer, NULL, NULL); + k_timer_start(&timer, K_MSEC(timeout), K_NO_WAIT); + + if (!gpio_is_ready_dt(spec)) { + goto cleanup; + } + + if (!gpio_pin_is_input_dt(spec)) { + goto cleanup; + } + + while(gpio_pin_get_dt(spec) == state) { + if (k_timer_status_get(&timer) > 0) { + goto cleanup; + } + } + + while(gpio_pin_get_dt(spec) != state) { + if (k_timer_status_get(&timer) > 0) { + goto cleanup; + } + } + + start = k_uptime_ticks(); + while(gpio_pin_get_dt(spec) == state) { + if (k_timer_status_get(&timer) > 0) { + goto cleanup; + } + } + end = k_uptime_ticks(); + + delta = k_ticks_to_us_floor64(end - start); + +cleanup: + k_timer_stop(&timer); + return (unsigned long)delta; +}