Arduino_Core_STM32 icon indicating copy to clipboard operation
Arduino_Core_STM32 copied to clipboard

Add support for ATOMIC_BLOCK

Open V10git opened this issue 1 month ago • 4 comments

My code uses avr-gcc util\atomic.h. For code block should be executed with disabled irqs and restore irqs state(disable, enable) after code block ends. Example:

ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
// some long time executed code irqs free
}

Can you add correct support of this to core? In my code I use this workaround(not tested):

#ifdef __ARM__
	#ifndef ATOMIC_BLOCK
		#define ATOMIC_BLOCK(type) for ( type, __ToDo = __iCliRetVal(); \
								__ToDo ; __ToDo = 0 )
		#define ATOMIC_RESTORESTATE uint8_t __primask_save \
			__attribute__((__cleanup__(__iRestore))) = __get_PRIMASK()

		static __inline__ uint8_t __iCliRetVal(void)
		{
			__disable_irq();
			return 1;
		}
		static __inline__ void __iRestore(const  uint8_t *__s)
		{
			__set_PRIMASK(*__s);
			__asm__ volatile ("" ::: "memory");
		}
	#endif
#endif

V10git avatar Oct 29 '25 23:10 V10git

This definition should correct work for code like this:

void someFunc()
{
   ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
      // some long time executed code irqs free
   } // irqs state not changed
}

void someFunc2()
{
   // irq disabled
   ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
      someFunc();
      // some long time executed code irqs free
   }  // irq enabled
}

V10git avatar Oct 30 '25 00:10 V10git

Hi @V10git Feel free to provides a PR.

fpistm avatar Nov 01 '25 10:11 fpistm

Hi @V10git Feel free to provides a PR.

I have 0 experience with stm32, so I don’t know how it should work on it correctly. Provided code example just cutoff from my project. I not test or compile it for now.

V10git avatar Nov 01 '25 11:11 V10git

Take a look at SimplyAtomic or the Teensy implementation

adbancroft avatar Nov 23 '25 13:11 adbancroft