superuser826 superuser826 - 2 months ago 6
C Question

Should I disable interrupts when executing code from RAM?

I am building an update function that completely erases my program code running out of program flash, and flashes a new image in its place. To accomplish this it is necessary to copy the update function into RAM and branch to it in its RAM location to perform the actual erase/program functions.

void update(){
//Erase flash
//Program flash
}

void main(){
// ...

ramfunction = copytoram((int)update);
ramfunction();
}


This process seems like it should be working to me but for some reason when I run through it, it is failing. I seem to be able to step through it with the debugger, but when I run it fails.

Should I be protecting
ramfunction();
by disabling interrupts perhaps? I do have other tasks running in the background. Are there any other probable issues?

Thanks so much!

Edit - All other tasks are running from flash. The update function is linked to run from flash also but I can successfully copy it to ram and branch to it. I can even step through it (at least the disassembly code), it is only when I run through it that I have problems.

Answer

If you have other tasks running simultaneously it is possible that they are interrupting the programming phase of ramfunction. This could result in catastrophic failure. I would try something like this:

void main(){
  // ...

  ramfunction = copytoram((int)update);
  disable_interrupts();
  ramfunction();
  enable_interrupts();
}