Using a 32.768kHz external crystal with Atmel XMEGA microcontroller RTC

I’ve just brought up a project using an Atmel XMEGA series microcontroller which uses an external 32.768kHz crystal to run its real time clock (RTC). I had some trouble getting it to work, but now I’ve found the recipe, thought I’d share it in case it’s useful to anyone.

DSC_0308

In principle, you’re supposed to enable the crystal oscillator and then wait until the XOSCRDY bit is set in the OSC.STATUS register, indicating that the oscillator has started up. My problem was that the oscillator seemed to be running, with a healthy-looking waveform at the XTAL1/TOSC1 pin, but the ready bit never got set.

DSC_0309

It turns out that the order of initialising the registers is important. You have to set XOSCCTRL first, to configure the oscillator, then enable it in CTRL, then wait for it to be ready. The code looks like this

OSC.XOSCCTRL= OSC_XOSCSEL_32KHz_gc;
OSC.CTRL|=OSC_XOSCEN_bm;
while(!(OSC.STATUS&OSC_XOSCRDY_bm));

That’s what worked for me. I’m using AVR Studio 6 and AVRGCC version 3.4.1.95.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s