Are interrupts turned off?
Using the correct stack for your part?
For GCC:
static __inline__ void *sp_get(void)
{
void *sp;
__asm__ __volatile__ ("mrs %0, msp" : "=r"(sp));
return( sp );
}
Replace msp with psp if using other stack.
A version in pure C that makes Lint explode for returning the address of a local variable:
/*
* void *CheckStackDepth( void )
* {
* volatile uint32_t dummy; // Put a variable on the stack
* return( (void *) &dummy ); // Return its address - therefore the (approx.) present SP value
* }
*/
Obscure GCC syntax for setting Link and Stack pointers:
static __inline__ void psp_set( void *setval )
{
__asm__ volatile ("msr psp, %[value]\n\t""dmb\n\t""dsb\n\t""isb\n\t"::[value]"r"(setval):);
__asm__ volatile ("" ::: "memory");
}
static __inline__ void lr_set(uint32_t setval)
{ __asm__ volatile ("mov lr, %[value]\n\t"::[value]"r"(setval):);
__asm__ volatile ("" ::: "memory");
}
Unless debugging is an obsession disable interrupts when doing any of the above operations:
See atomic.h.zip in this tread for the GCC ARM code to do save/restore of the IRQ state.
https://community.nxp.com/message/816609?commentID=816609#comment-816609