// Copyright (c) 2001-2005 Rowley Associates Limited.
//
// This file may be distributed under the terms of the License Agreement
// provided with this software.
//
// THIS FILE IS PROVIDED AS IS WITH NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
////////////////////////////////////////////////////////////////////////////////
//
//                          TMS470 - UART Example
//
// Description
// -----------
// This example demonstrates configuring and writing to a UART. It also
// demonstrates how to get printf output over the UART by implementing
// __putchar.
//
// To see output:
//   - Connect serial cable from RS232_1 connector on your target board to your
//     host computer.
//   - Open CrossStudio's "Terminal Emulator Window". Configure it to 9600 baud,
//     8 data bits, no parity, 1 stop bits. Click "Connect" to start the
//     terminal emulator window.
//      
////////////////////////////////////////////////////////////////////////////////
    
#include <targets/TMS470.h>

#define OSCILLATOR_FREQUENCY 12000000

static void
UARTInitialize(unsigned long baudrate)
{
  unsigned long iclk_freq = OSCILLATOR_FREQUENCY / ((PCR >> 1) + 1);
  unsigned long divisor = (iclk_freq / 8 / baudrate) - 1;
  SCI1CTL3 &= 0x7f; /* Reset the SCI */
  SCI1CCR = 0x17; /* 8 bit / asynchronous timing */
  SCI1CTL1 |= 0x01; /* Enable RX */
  SCI1CTL2 |= 0x01; /* Enable TX */
  SCI1CTL3 |= 0x20; /* Internal SCICLK */
  SCI1HBAUD = (unsigned char)(divisor >> 16);
  SCI1MBAUD = (unsigned char)(divisor >> 8);
  SCI1LBAUD = (unsigned char)divisor;
  SCI1PC2 |= 0x02; /* SCIRX is the SCI receive pin */
  SCI1PC3 |= 0x02; /* SCITX is the SCI transmit pin */
  SCI1CTL3 |= 0x80; /* Enable TX/RX */
}

static void
UARTWriteChar(char ch)
{
  while (!(SCI1CTL2 & 0x04));
  SCI1TXBUF = ch;
}

static unsigned char
UARTReadChar(void)
{
  while (!(SCI1CTL1 & 0x04));
  return SCI1RXBUF;
}

static int
UARTReadAvailable(void)
{
  return SCI1CTL1 & 0x04;
}

void
__putchar(int ch)
{
  if (ch == '\n')
    UARTWriteChar('\r');
  UARTWriteChar(ch);
}

int
main(void)
{
  int i;

  PCR = 1; /* Set ICLK to 12Mhz */

  UARTInitialize(9600);

  for (i = 0; ; ++i)
    {
      printf("Hello World (%d)\n", i++);
      if (UARTReadAvailable())
        {
          char ch = UARTReadChar();
          if (ch == 'q' || ch == 'Q')
            break;
          printf("Key \'%c\' pressed\n", ch);
        }
    }

  printf("Quit\n");
  return 0; 
}
