// 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.
//
////////////////////////////////////////////////////////////////////////////////
//
//                    Revely RMS100 - 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 the UART 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/LH754xx.h>

#define UART_CLOCK_FREQUENCY 14745600

static void
UARTInitialize(unsigned int baud)
{
  unsigned int divisor = UART_CLOCK_FREQUENCY / (16 * baud);
  IOCON_PD_MUX |= 0x0050; /* Setup port pins */
  RCPC_APBPeriphClkCtrl0 &= ~3; /* Enable clock to UART1 */
  UART1_FBRD = 0;
  UART1_IBRD = divisor;
  UART1_ICR = 0x07f0;
  UART1_ECR = 0;
  UART1_IMSC = 0;
  UART1_LCR_H = 0x70; /* 8 bit, 1 stop bit, no parity */
  UART1_CTRL = 0x301; /* Enable transmit and receive */
}

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

static unsigned char
UARTReadChar(void)
{
  while (UART1_FR & 0x10);
  return UART1_DR;
}

static int
UARTReadAvailable(void)
{
  return (UART1_FR & 0x10) == 0;
}

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

int
main(void)
{
  int i, j;
  UARTInitialize(9600);
  for (i = 0, j= 0; ; ++i)
    {
      if ((i % 2000) == 0)
        printf("Hello World (%d)\n", j++);
      if (UARTReadAvailable())
        { 
          char ch = UARTReadChar();
          if (ch == 'q' || ch == 'Q')
            break;
          printf("Key \'%c\' pressed\n", ch);
        }
    }
  printf("Quit\n");
  return 0; 
}

