From 31c4a26d82c073c3a7c1634cfe29ffd1ac6ffc58 Mon Sep 17 00:00:00 2001 From: Alex Voinea Date: Sun, 9 Oct 2022 22:11:36 +0200 Subject: [PATCH] Make gpio write atomic Unfortunately, there is no way to differentiate between an optimized gpio write (safe always on the atmega32u4) and an unoptimized write (read-modify-write, dangerous if any other pin on that Port is used in an ISR). While very quickly polling the tmc registers, I noticed that the moving stepper would do some random extra steps. That can only be explained by the following sequence of actions: - the spi code reads the PORT register - ISR toggles the step line, changing the value in the PORT register - the spi code writes the upated PORT back, resetting the step line to the old state After making the writes atomic, the stepping issue disappeared and the driver checks also worked correctly --- src/hal/gpio.h | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/hal/gpio.h b/src/hal/gpio.h index 1311891..59506b6 100644 --- a/src/hal/gpio.h +++ b/src/hal/gpio.h @@ -1,6 +1,7 @@ /// @file gpio.h #pragma once #include +#include #ifdef __AVR__ #include @@ -53,10 +54,12 @@ struct GPIO_pin { }; __attribute__((always_inline)) inline void WritePin(const GPIO_pin portPin, Level level) { - if (level == Level::high) - portPin.port->PORTx |= (1 << portPin.pin); - else - portPin.port->PORTx &= ~(1 << portPin.pin); + ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { + if (level == Level::high) + portPin.port->PORTx |= (1 << portPin.pin); + else + portPin.port->PORTx &= ~(1 << portPin.pin); + } } __attribute__((always_inline)) inline Level ReadPin(const GPIO_pin portPin) {