// Copyright (c) 2001-2004 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.
//
////////////////////////////////////////////////////////////////////////////////
//
//                    Philips LPC210X - 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 UART0 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/LPC210x.h>

static unsigned int
processorClockFrequency(void)
{
  return OSCILLATOR_CLOCK_FREQUENCY * (PLLCON & 1 ? (PLLCFG & 0xF) + 1 : 1);
}

static unsigned int
peripheralClockFrequency(void)
{
  unsigned int divider;
  switch (VPBDIV & 3)
    {
      case 0:
        divider = 4;
        break;
      case 1:
        divider = 1;
        break;
      case 2:
        divider = 2;
        break;
    }
  return processorClockFrequency() / divider;
}

static void
delay(int n)
{
  volatile int i;
  for (i = 0; i < n; ++i);
}

static void
UARTInitialize(unsigned int baud)
{
  unsigned int divisor = peripheralClockFrequency() / (16 * baud);
  U0LCR = 0x83; /* 8 bit, 1 stop bit, no parity, enable DLAB */
  U0DLL = divisor & 0xFF;
  U0DLM = (divisor >> 8) & 0xFF;
  U0LCR &= ~0x80; /* Disable DLAB */
  PINSEL0 = PINSEL0 & ~0xF | 0x5;
  U0FCR = 1;
}

static void
UARTWriteChar(unsigned char ch)
{
  while ((U0LSR & 0x20) == 0);
  U0THR = ch;
}

static unsigned char
UARTReadChar(void)
{
  while ((U0LSR & 0x01) == 0);
  return U0RBR;
}

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

int
main(void)
{
  int i;
  UARTInitialize(9600);
  delay(1000);
  for (i = 0; ; ++i)
    printf("Hello World (%d)\n", i);
  return 0; 
}

