// 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.
//
////////////////////////////////////////////////////////////////////////////////
//
//                       Atmel EB55 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 SERIAL A on the EB55 board to your host
//     computer.
//   - Open CrossStudio's "Terminal Emulator Window". Configure it to 4800 baud, 
//     8 data bits, no parity, 2 stop bits. Click "Connect" to start the
//     terminal emulator window.
//
////////////////////////////////////////////////////////////////////////////////

#include <targets/AT91SAM7A1.h>

#define CORECLK_FREQUENCY 30000000

static void
UARTInitialize(unsigned long baudrate)
{
  US0_ECR = 0x00000003; // Enable USART clock
  US0_CR = 0x0000010D; // Reset
  US0_PDR = 0x00070000; // Disable USART PIO
  US0_MR = 0x000008C0; // CORECLK, 8 bit, asynchronous, no parity, 1 stop bit, normal mode
  US0_BRGR = CORECLK_FREQUENCY / (16 * baudrate);
  US0_CR = 0x00000050; // Enable TX and RX
}

static void
UARTWriteChar(char ch)
{
  while (!(US0_SR & 0x00000002)); // Wait for TXRDY
  US0_THR = ch;
}

static char
UARTReadChar()
{
  while (!(US0_SR & 0x00000001)); // Wait for RXRDY
  return (char)US0_RHR;
}

static int
UARTReadAvailable(void)
{
  return US0_SR & 0x00000001;
}

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