Tuesday, August 6, 2013

atxmega enable 32Mhz internal oscillator

The atxmega (I'm playing with an atxmega16e5) has multiple internal oscillators. By default it starts on the 2Mhz clock, which is actually an 8Mhz internal oscillator divided by 4. The following code switches to the 32Mhz internal oscillator.

register definitions can be found in iox16e5.h. As I'm using an older avr-gcc I've looked in iox16d4.h instead, assuming that the base registers like for the clock are the same.

#include <avr io.h>
#include <util delay.h>

int main( void )
{
  // enable 32Mhz internal oscillator
  OSC.CTRL|=OSC_RC32MEN_bm;
  // wait for the oscillator to stabilize
  while (!(OSC.STATUS & OSC_RC32MRDY_bm)); 
  // tell the processor we want to change a protected register
  CCP=CCP_IOREG_gc;
  // and start using the 32Mhz oscillator
  CLK.CTRL=CLK_SCLKSEL_RC32M_gc; 
  // finally disable the default 2Mhz oscillator (optional)
  OSC.CTRL&=(~OSC_RC2MEN_bm);

  // set PA0 as output
  PORTA.DIRSET = 0b00000001;
  
  // blink LED on PA0 with 1 second on, 1 second off
  while (1) {
    PORTA.OUTSET = 0b00000001 ;
    _delay_ms( 1000 )
    PORTA.OUTCLR = 0b00000001 ;
    _delay_ms( 1000 )
  }
}

No comments: