// 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.
//
////////////////////////////////////////////////////////////////////////////////
//
//                      Cogent CSB637 UART Example
//
// Description
// -----------
// This example demonstrates configuring and writing to the DBG UART. It also 
// demonstrates how to get printf output over the UART by implementing 
// __putchar.
//
// To see output:
//   - Connect serial cable from DBG connector on the board to your host
//     computer.
//   - Open CrossStudio's "Terminal Emulator Window". Configure it to 9600 baud, 
//     8 data bits, no parity, 1 stop bit. Click "Connect" to start the
//     terminal emulator window.
//
////////////////////////////////////////////////////////////////////////////////

#include <targets/AT91RM9200.h>

#define PROCESSOR_CLOCK_FREQUENCY 184320000
#define MCK_FREQUENCY (PROCESSOR_CLOCK_FREQUENCY / 4)

static void
UARTInitialize(unsigned long baudrate)
{
  DBGU_CR = DBGU_CR_RSTSTA | DBGU_CR_RSTTX | DBGU_CR_RSTRX;
  DBGU_BRGR = MCK_FREQUENCY / (16 * baudrate);
  DBGU_MR = 4 << DBGU_MR_PAR_BIT; /* No parity */
  DBGU_CR = DBGU_CR_TXEN | DBGU_CR_RXEN;

  /* Configure PA30:31 to be DRXD and DTXD */
  PIOA_PDR |= 0xC0000000;
  PIOA_ASR |= 0xC0000000;
  PIOA_BSR &= ~0xC0000000;
}

static void
UARTWriteChar(char ch)
{
  while (!(DBGU_SR & DBGU_SR_TXRDY));
  DBGU_THR = ch;
}

static char
UARTReadChar()
{
  while (!(DBGU_SR & DBGU_SR_RXRDY));
  return (char)DBGU_RHR;
}

static int
UARTReadAvailable(void)
{
  return DBGU_SR & DBGU_SR_RXRDY;
}

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

int
main(void)
{
  int i;

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

  return 0; 
}
