Arduino Community Logo: Arduino.landARDUINO.LANDCODE LIBRARIESAtomicBlock

AtomicBlock C++ Library for AVR Processors

About

Recently I have been working on a project that requires safety from interrupts so after a bit of research I found the ATOMIC_BLOCK macros. They seem to be widely accepted as an easy way of controlling the global interrupt flag. After using the macros for a while I decided the syntax created from using the macros, even though understandable, is not a standard construct with respect to 'loops' and 'if' statements, and it looks like a function definition nested inside another function, which is not allowed in C++. Also, I have a need for some objects to be able to automatically control their atomic operations, I needed a more user friendly approach.

The main principle I have come up with is quite simple. All you have to do is declare a variable of the class of blocking operation you wish to use, it works purely on side effects. The atomic operation lasts for the lifetime of the variable, therefore you can return from a function and still expect the global interrupt flag to be restored. This removes the need to store the status value while the interrupt flag is being restored before return.
As of version 1.1, The function 'Protect' was added to the blocking classes. It is described in detail below.

ATOMIC_BLOCK Usage

This is a short snippet showing how the original ATOMIC_BLOCK macros function.

void loop()
	{
		ATOMIC_BLOCK( ATOMIC_RESTORESTATE ){

			NONATOMIC_BLOCK( NONATOMIC_FORCEOFF ){

			}
		}
		return;
	}

AtomicBlock Usage
void loop()
	{
		AtomicBlock< Atomic_RestoreState > a_Block;
		{
			NonAtomicBlock< Atomic_Force > a_NoBlock;

		}
		return;
	}

Usage

The Protect Function.

Each blocking type contains a function named 'Protect'. It can be used to protect any kind of element.

Efficient implementation.

As the system is template based the compiler has all the information it need to remove unnecessary code.

Tags
Source
Comments

Comment system coming soon.

Designed & created by Christopher Andrews. 2014