Embedded Freaks..

September 19, 2008

Asynchronous Timer / RTC demo for AVR

Filed under: avr — Tags: — kunilkuda @ 5:30 pm

After some time with the Java, it’s time to go back to the AVR. I need to test it’s current consumption while sleeping. So, here’s some simple demo to turn on/off the RTC in AVR’s Timer 0

/**
 * AVR asynchronous timer / RTC demo
 *
 * Tested with ATMega128L with:
 * - RTC xtal (32.768 kHz) at TOSC1/PG4 and TOSC2/PG3 pins
 * - Red LED at PA2
 * - Green LED at PA1
 * - Yellow LED at PA0
 */
#include <avr/io.h>
#include <avr/signal.h>
#include <avr/interrupt.h>

/**
 * Initialize Timer 0 as async clock
 */
void initAsyncTimer(void)
{
  // Enable output compare interrupt
  TIMSK |= (1 << OCIE0);

  // Set mode to CTC
  TCCR0 |= (1 << WGM01);

  // Enable asynchronous mode
  ASSR |= (1 << AS0);
}

/**
 * Start timer 0.
 * Enable it to shot periodically with x second interval
 *
 * \param second Interval, from 1 to 7 seconds
 */
void startTimer(uint8_t second)
{
  // We use 32.768kHz / 1024 prescaled clock
  uint16_t temp = second * 32;
  OCR0 = (uint8_t) temp;

  // Start timer with 1024 prescaler
  TCCR0 |= (7 << CS00);
}

/**
 * Stop timer 0.
 */
void stopTimer(void)
{
  TCCR0 &= ~(7 << CS00);
  OCR0 = 0;
}

/**
 * Toggle Yellow LED
 */
void toggleYellowLed(void)
{
  DDRA |= (1 << PA0);

  if ((PORTA & (1 << PA0)) > 0) {
    PORTA &= ~(1 << PA0);
  }
  else {
    PORTA |= (1 << PA0);
  }
}

int main(void)
{
  initAsyncTimer();

  // Start the timer with 7-sec period
  startTimer(7);

  sei();

  while(1);
  return 0;
}

SIGNAL(SIG_OUTPUT_COMPARE0)
{
  toggleYellowLed();
}

The schematic will be posted later, if I got a chance to update this posting.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: