// Copyright (c) 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.

#include "test.h"
#include <ctl_api.h>
#include <targets/LH79520.h>

#define EINT1_INT 15
#define UART0_INT 23

#define UART_CLOCK_FREQUENCY 14745600

static void
UARTInitialize(unsigned int baud)
{
  unsigned int divisor = UART_CLOCK_FREQUENCY / (16 * baud);
  UARTMux |= 0x3; /* Setup port pins */
  PeriphClkCtrl &= ~1; /* Enable clock to UART1 */
  PeriphClkSelect &= ~1; /* Use internal clock */
  UART0IBRD = divisor;
  UART0FBRD = 0;
  UART0LCR_H = 0x70; /* 8 bit, 1 stop bit, no parity */
  UART0CR = 0x301; /* Enable transmit and receive */
}

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

static unsigned char
UARTReadChar(void)
{
  while (UART0FR & 0x10);
  return UART0DR;
}

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

void
BoardInit(void)
{
  GPIOPFDDR |= 2;
  GPIOPFDR &= ~2;
}

unsigned long
TicksPerSecond(void)
{
  return 1000;
}

static CTL_ISR_FN_t userButtonISR;
static void
buttonISR(void)
{
  userButtonISR();
  while (UARTReadAvailable())
    UARTReadChar();
}

void
SetButtonPressedISR(CTL_ISR_FN_t isr)
{
  userButtonISR = isr;
  UARTInitialize(9600);
  UART0IMSC |= 0x10;
  UART0IFLS = 0;
  ctl_set_isr(UART0_INT, 1, CTL_ISR_TRIGGER_FIXED, buttonISR, 0);
  ctl_unmask_isr(UART0_INT);
}

void
SetLeds(unsigned v)
{
  if (v)
    GPIOPFDR &= ~2;
  else
    GPIOPFDR |= 2;
}
