Best way to do protected write?

Go To Last Post
5 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I'm working with the AVR128DB28 and AVR128DB48.  In some cases, like when changing configuration of the oscillators, a protected write is needed.  I've seen protected write in two different forms:

 

_PROTECTED_WRITE(CLKCTRL.OSC32KCTRLA, CLKCTRL_RUNSTDBY_bm);  // enable internal 32K osc  

ccp_write_io((void*)&CLKCTRL.OSC32KCTRLA, CLKCTRL_RUNSTDBY_bm);    // enable internal 32K osc 

What is the difference between the two forms and is one form more preferable than the other?

 

 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0


I don't know what the other advantages and disadvantages are, but here's why I use _PROTECTED_WRITE:

1. You must include cpufunc.h to use ccp_write_io. _PROTECTED_WRITE is included in xmega.h, but no include description is required.

2. _PROTECTED_WRITE is smaller and faster than the build result.

 

sample:

#include <avr/io.h>
#include <avr/cpufunc.h>

int main(void){
    _PROTECTED_WRITE(CLKCTRL.OSCHFCTRLA, CLKCTRL_FREQSEL_24M_gc);
    asm("nop");

    ccp_write_io((uint8_t*)&CLKCTRL.OSCHFCTRLA, CLKCTRL_FREQSEL_24M_gc);
    asm("nop");
    
    while (1);
}

LSS:

 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

The macro is probably better as the function version is a library function that will get called, and the difference basically boils down to doing a sts in the macro version vs doing a call in the library function version (and you still are not done)-

 

https://godbolt.org/z/nWcbdKbvo

(mega4809, but close enough)

 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

kabasan wrote:

1. You must include cpufunc.h to use ccp_write_io. _PROTECTED_WRITE is included in xmega.h, but no include description is required.

2. _PROTECTED_WRITE is smaller and faster than the build result.

 

Thanks for this.  And your assembly listing is very helpful!

 

Paul

 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

curtvm wrote:
The macro is probably better as the function version is a library function

 

Thank you.

 

Paul