Wednesday, November 3, 2010

Enabling 32MHz Operation on the AVR XMEGA


I received an AVR XMega100 Breakout from SparkFun in the mail yesterday and I've started doing some experimenting with it. The first problem I ran across was getting into 32MHz clock mode. The XMegas have a internal oscillator but by default they are set to 2MHz operation. What's kind of neat about the XMegas though is that you can switch the speed at runtime. What tripped me up was the fact that the registers that control the oscillator and clock are both protected registers. I'm not really sure what the benefit of this is but in any case here is the code to enter 32MHz mode.

void setClockTo32MHz() {
    CCP = CCP_IOREG_gc;              // disable register security for oscillator update
    OSC.CTRL = OSC_RC32MEN_bm;       // enable 32MHz oscillator
    while(!(OSC.STATUS & OSC_RC32MRDY_bm)); // wait for oscillator to be ready
    CCP = CCP_IOREG_gc;              // disable register security for clock update
    CLK.CTRL = CLK_SCLKSEL_RC32M_gc; // switch to 32MHz clock
}

A couple things to note. Check that you set the clock speed (F_CPU) in your compile to 32000000. And since the clock can be modified at runtime, anything that relies on the F_CPU constant may be effected, this includes the build in delay functions. For what I'm doing I'm not concerned with switching back and forth but some low power applications may find that useful.