/*
 * $Id: main.c,v 1.6 2007/08/02 01:18:44 bsd Exp $
 *
 */

/*
 * SP03 - a complete test program using the SP03 on the BDMICRO MAVRIC
 * and MAVRIC-II microcontroller boards.  This program is intended to
 * demonstrate how to use the BDMICRO MAVRIC or MAVRIC-II
 * microcontroller boards to talk to the SP03.  Feel free to copy the
 * relevent function definitions into your own applications and to
 * customize them for your needs.
 *
 * See: http://www.bdmicro.com/
 *
 * Configuration:
 *
 *   Simply attach your SP03 speach module to your board's I2C bus,
 *   power, and round.  It's OK to use one of the supplied VCC pins on
 *   your microcontroller board to supply power to the SP03.
 *
 * */

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/twi.h>

#include "i2c.h"
#include "sp03.h"


#define CPU_FREQ 16000000L  /* set to clock frequency in Hz */

#if CPU_FREQ == 16000000L
#define OCR_1MS 125
#elif CPU_FREQ == 14745600L
#define OCR_1MS 115
#endif


volatile uint16_t ms_count;

/*
 * ms_sleep() - delay for specified number of milliseconds
 */
void ms_sleep(uint16_t ms)
{
  TCNT0  = 0;
  ms_count = 0;
  while (ms_count != ms)
    ;
}


/* 
 * millisecond counter interrupt vector 
 */
SIGNAL(SIG_OUTPUT_COMPARE0)
{
  ms_count++;
}


/*
 * Initialize timer0 to use the main crystal clock and the output
 * compare interrupt feature to generate an interrupt approximately
 * once per millisecond to use as a general purpose time base.
 */
void init_timer0(void)
{
  TCCR0 = 0;
  TIFR  |= _BV(OCIE0)|_BV(TOIE0);
  TIMSK |= _BV(TOIE0)|_BV(OCIE0);         /* enable output compare interrupt */
  TCCR0  = _BV(WGM01)|_BV(CS02)|_BV(CS00); /* CTC, prescale = 128 */
  TCNT0  = 0;
  OCR0   = OCR_1MS;                     /* match in aprox 1 ms */
}





int main(void)
{
  init_timer0();

  /* enable interrupts */
  sei();

  /* set the I2C bit rate generator to 100 kb/s */
  TWSR &= ~0x03;
  TWBR  = 28;
  TWCR |= _BV(TWEN);

  /* speak message */
  speak("Welcome to the BD micro SP03 test program");
  wait4shutup();         /* wait until the SP03 is done talking */
  ms_sleep(512);         /* wait another .5 seconds */
  speak("Hello world!"); /* talk again */

  while (1)
    ;

}

