Skip to content

Instantly share code, notes, and snippets.

@standarddeviant
Last active April 19, 2018 15:03
Show Gist options
  • Save standarddeviant/2355325cbaefc8df0ac0efffe4ea6b11 to your computer and use it in GitHub Desktop.
Save standarddeviant/2355325cbaefc8df0ac0efffe4ea6b11 to your computer and use it in GitHub Desktop.
Trying to figure out where how to user interrupts safely on a a MKRZERO
#include <SD.h>
// START https://mcuoneclipse.com/2014/01/26/entercritical-and-exitcritical-why-things-are-failing-badly/
#define CpuCriticalVar() uint8_t cpuSR
#define CpuEnterCritical() \
do { \
asm ( \
"MRS R0, PRIMASK\n\t" \
"CPSID I\n\t" \
"STRB R0, %[output]" \
: [output] "=m" (cpuSR) :: "r0"); \
} while(0)
#define CpuExitCritical() \
do{ \
asm ( \
"ldrb r0, %[input]\n\t" \
"msr PRIMASK,r0;\n\t" \
::[input] "m" (cpuSR) : "r0"); \
} while(0)
#if 0 /* original, buggy version */
#define DEFINE_CRITICAL() /* nothing */
#define ENTER_CRITICAL() EnterCritical()
#define EXIT_CRITICAL() ExitCritical()
#else /* fixed version using local variable */
#define DEFINE_CRITICAL() CpuCriticalVar()
#define ENTER_CRITICAL() CpuEnterCritical()
#define EXIT_CRITICAL() CpuExitCritical()
#endif
// END https://mcuoneclipse.com/2014/01/26/entercritical-and-exitcritical-why-things-are-failing-badly/
volatile unsigned short volatile_ushort;
void an_isr() {
volatile_ushort++;
}
void setup() { // attach the interrupt to an_isr
attachInterrupt(digitalPinToInterrupt(6), an_isr, LOW);
}
void loop() {
DEFINE_CRITICAL();
static unsigned short local_ushort = 0;
ENTER_CRITICAL();
local_ushort = volatile_ushort;
EXIT_CRITICAL();
Serial.println(local_ushort);
delay(500);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment