Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Need to disable interrupts when setting output pins or modifying registers in order to enforce atomic access #2

Open
ElectricRCAircraftGuy opened this issue Feb 21, 2019 · 0 comments

Comments

@ElectricRCAircraftGuy
Copy link
Owner

ElectricRCAircraftGuy commented Feb 21, 2019

This:

//FOR SPEED PROFILING WITH OSCILLOSCOPE
//-Don't forget that a direct-port-access write like this takes 2 clock cycles, or 0.125 us, so you have to subtract
//2 clock cycles (NOT 4) from whatever time period you profile with the oscilloscope.
#define PROFILE_PIN2_HIGH   PORTD |= _BV(2)  //write Arduino pin D2 HIGH
#define PROFILE_PIN2_LOW    PORTD &= ~_BV(2) //write Arduino pin D2 LOW

is written incorrectly. |= and &= are NOT atomic operations, so technically interrupts should be disabled and enabled again. Implement a macro which uses a do while loop to automatically do that for me, utilizing the following:

uint8_t SREG_bak = SREG;
cli();
// do your pin change
SREG = SREG_bak;

See here for an example:

	uint8_t oldSREG = SREG;
	cli();

	if (val == LOW) {
		*out &= ~bit;
	} else {
		*out |= bit;
	}

	SREG = oldSREG;

Source: https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/wiring_digital.c

NOTE: do this ANYWHERE in the code you use &= or |=, as NONE of those operations are automatically atomic, so you need to add atomic access guards for all of them to force atomicity.

@ElectricRCAircraftGuy ElectricRCAircraftGuy changed the title Need to disable interrupts when setting output pins Need to disable interrupts when setting output pins or modifying registers in order to enforce atomic access Feb 21, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant