// 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.
//
////////////////////////////////////////////////////////////////////////////////
//
//                      ST STA2051 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 UART 0 on the target board to your host 
//     computer.
//   - Open CrossStudio's "Terminal Emulator Window". Configure it to 4800 baud, 
//     8 data bits, no parity, 1 stop bits. Click "Connect" to start the
//     terminal emulator window.
//
////////////////////////////////////////////////////////////////////////////////

#include <targets/STA2051.h>

#define PROCESSOR_CLOCK_FREQUENCY 32000000

#include <stdio.h>

static void
UARTInitialize(unsigned long baudrate)
{
  UART0_ASCControl = 0;
  UART0_ASCBaudRate = PROCESSOR_CLOCK_FREQUENCY / (16 * baudrate);
  UART0_ASCControl = 0x589;
}

static void
UARTWriteChar(char ch)
{
  while (!(UART0_ASCStatus & 0x2));
  UART0_ASCTxBuffer = (char)ch;  
}

static unsigned char
UARTReadChar(void)
{
  while (!(UART0_ASCStatus & 0x1));
  return UART0_ASCRxBuffer;
}

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

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

int
main(void)
{
  int i;

  /* Configure P0.8 and P0.9 as U0.RX and U0.TX */
  IOPORT0_PC0 |= 0x300;
  IOPORT0_PC1 |= 0x200;
  IOPORT0_PC1 &= ~0x100;
  IOPORT0_PC2 |= 0x200;
  IOPORT0_PC2 &= ~0x100;

  UARTInitialize(4800);

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