/*
 *  timer.c
 *
 *  This times a small section of code using TIMER1 on the ColdFire.
 *
 *  Author:
 *    David Fiddes, D.J@fiddes.net
 *    http://fiddes.net/coldfire/
 *
 *  This code has no copyright and may freely be used in whatever 
 *  manner you see fit.
 *
 *  THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY 
 *  OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT    
 *  LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR    
 *  FITNESS FOR A PARTICULAR PURPOSE.                              
 */
#include <stdio.h>

#ifdef MCF5307
  #include "sim5307.h"

  volatile SIM5307 *sim = (SIM5307 *)0x10000000;
#else
  #include "sim5206.h"

  volatile SIM5206 *sim = (SIM5206 *)0x10000000;
#endif

/* We substitute iprintf for printf to avoid bringing in the floating point library */
/* The functions are otherwise equivalent */
#define printf iprintf

/* prototypes for functions in this module */
void  ResetTimer( void );
void  StopTimer ( void );
short ReadTimer( void );
void  StartTimer16( void );
void  StartTimer256( void );
void  program( void );



void ResetTimer( void )
{

  sim->timer1.tmr = sim->timer1.tmr | 0x0001; /* enable timer */
  sim->timer1.tmr = sim->timer1.tmr | 0x0000; /* reset timer  */
  sim->timer1.tmr = sim->timer1.tmr | 0x0001; /* re-enable timer */
  sim->timer1.tcn = 0; /* zero count */
}

void StopTimer ( void )
{
  sim->timer1.tmr = sim->timer1.tmr & 0xFFF9; /* input clock bits = 00 to stop timer */
}

short ReadTimer( void )
{
  return sim->timer1.tcn; /* just return the timer counter register */
}

void StartTimer16( void )
{
  sim->timer1.tmr = (sim->timer1.tmr & 0xFFF9) | 0x0004; /* Set Master_Clk/16 and start */
}

void StartTimer256( void )
{
  sim->timer1.tmr = (sim->timer1.tmr & 0x00FF) | 0xFF00; /* Set prescale to 1/256 */
}

void program( void )
{
  int i;

  for ( i = 0; i<300; i++)
  {
    printf("Hello World");   /* something to waste time */
  }
}


int main()
{
  printf("Timer1 test program\n\n");

  printf("About to reset timer...\n");
  ResetTimer();

  printf("About to set timer to 1/256...\n");
  StartTimer256();

  printf("About to start timer...\n");
  StartTimer16();

  printf("About to run the main program...\n");
  program();

  printf("\nAbout to stop timer...\n");
  StopTimer();

  printf("The timer recorded %d ticks\n",ReadTimer());
  
  return 0;
}












