// 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.
//
////////////////////////////////////////////////////////////////////////////////
//
//          Logic Product Development SDKLH75401-10 - 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 UART2_CLOCK_FREQUENCY 51610000 

static void
UARTInitialize(unsigned int baud)
{
  unsigned int divisor = UART2_CLOCK_FREQUENCY / (16 * baud);
  IOCON_PE_MUX |= 0x3; /* Setup port pins */
  RCPC_APBPeriphClkCtrl0 &= ~4; /* Enable clock to UART2 */
  UART2_LCR = 0x0; /* DLAB = 0 */
  UART2_GIR = 3 << 5; /* Select register bank 3 */
  UART2_BACF = 4; /* Enable BRGA baudrate generator mode */
  UART2_CLCF = 0x50; /* Set BRGA as clock source */
  UART2_GIR = 0; /* Select register bank 0 */
  UART2_LCR = 0x80; /* DLAB = 1 */
  UART2_BAL = (unsigned char)divisor; /* Set divisor LSB */
  UART2_BAH = (unsigned char)(divisor >> 8); /* Set divisor MSB */
  UART2_LCR = 3; /* DLAB = 0, 8 bit, 1 stop bit, no parity */
}

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

static unsigned char
UARTReadChar(void)
{
  while ((UART2_LSR & 0x1) == 0);
  return UART2_RXD;
}

static int
UARTReadAvailable(void)
{
  return UART2_LSR & 0x1;
}

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)
    {
      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; 
}

