Skip to content

Commit

Permalink
zephyrCommon: Implement pulseIn
Browse files Browse the repository at this point in the history
- A basic sync implementation
- Use ticks for better resolution

Signed-off-by: Ayush Singh <ayushdevel1325@gmail.com>
  • Loading branch information
Ayush1325 committed Jun 13, 2024
1 parent 347a80d commit 28ef76c
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions cores/arduino/zephyrCommon.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

0 comments on commit 28ef76c

Please sign in to comment.