From 72e67f0f027e6427b14b5cd126d6d9edd832e3d2 Mon Sep 17 00:00:00 2001 From: robert-hh Date: Mon, 20 Oct 2025 08:52:18 +0200 Subject: [PATCH] samd/machine_bitstream: Tune ticks for SAMD51 and set pin to output. Changes in this commit: - Change ticks overhead value for SAMD51. The value was too large and thus timing was quite bad. At 120Mhz it's now within +/- 30ns. - Set the pin to output mode. That way, all Pin identifiers are accepted as argument, not only Pin objects. Tested with ItsyBitsy M4 and M0 boards. Signed-off-by: robert-hh --- ports/samd/machine_bitstream.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/ports/samd/machine_bitstream.c b/ports/samd/machine_bitstream.c index 9959d947cb..e6a50da682 100644 --- a/ports/samd/machine_bitstream.c +++ b/ports/samd/machine_bitstream.c @@ -36,7 +36,7 @@ // No cycle counter on M0, do manual cycle counting instead. -// STM32F091 @ 48MHz +// SAMD21 @ 48MHz #define NS_CYCLES_PER_ITER_HIGH (3) #define NS_CYCLES_PER_ITER_LOW (3) #define NS_OVERHEAD_CYCLES_HIGH (12) @@ -52,6 +52,7 @@ void machine_bitstream_high_low(mp_hal_pin_obj_t pin, uint32_t *timing_ns, const volatile const uint32_t mask = 1 << (pin % 32); volatile uint32_t *outclr = &PORT->Group[pin / 32].OUTCLR.reg; volatile uint32_t *outset = &PORT->Group[pin / 32].OUTSET.reg; + mp_hal_pin_output(pin); // Convert ns to loop iterations [high_time_0, low_time_0, high_time_1, low_time_1]. for (size_t i = 0; i < 4; ++i) { @@ -163,11 +164,12 @@ void machine_bitstream_high_low(mp_hal_pin_obj_t pin, uint32_t *timing_ns, const #else // > CORTEX_M0 -#define NS_TICKS_OVERHEAD (70) +#define NS_TICKS_OVERHEAD (40) void machine_bitstream_high_low(mp_hal_pin_obj_t pin, uint32_t *timing_ns, const uint8_t *buf, size_t len) { uint32_t fcpu_mhz = get_cpu_freq() / 1000000; uint32_t ticks_overhead = fcpu_mhz * NS_TICKS_OVERHEAD / 1000; + mp_hal_pin_output(pin); // Convert ns to us ticks [high_time_0, period_0, high_time_1, period_1]. for (size_t i = 0; i < 4; ++i) { timing_ns[i] = fcpu_mhz * timing_ns[i] / 1000; @@ -191,8 +193,8 @@ void machine_bitstream_high_low(mp_hal_pin_obj_t pin, uint32_t *timing_ns, const mp_hal_pin_high(pin); while ((mp_hal_ticks_cpu() - start_ticks) < t[0]) { } - b <<= 1; mp_hal_pin_low(pin); + b <<= 1; while ((mp_hal_ticks_cpu() - start_ticks) < t[1]) { } }