/***************************************************************************/
/*  Description      : UART driver for the NXP LPC1xxx microcontrollers.   */
/*                                                                         */
/*                  (C) Copyright 2010 NXP Semiconductors                  */
/*                                                                         */
/***************************************************************************/

#include <LPC11Uxx.h>                          // LPC11Uxx definitions
#include "uart.h"

const char ascii[] = "0123456789ABCDEF";

void UART_Init(LONG baudrate)
{
  LONG brd = (SystemCoreClock / (baudrate << 4));

    LPC_IOCON->PIO0_18 = 0x81;                 // UART RXD
    LPC_IOCON->PIO0_19 = 0x81;                 // UART TXD

    LPC_SYSCON->SYSAHBCLKCTRL |= (1<<12);      // Enable USART clock
    LPC_SYSCON->UARTCLKDIV     = 1;            // divided by 1

    LPC_USART->FCR = 0x07;                     // Enable and reset TX and RX FIFO
    LPC_USART->LCR = 0x83;                     // 8 bits, no Parity, 1 Stop bit
    LPC_USART->DLL = (brd & 0xFF);             // Set baud rate dividers
    LPC_USART->DLM = (brd >> 8);               //
    LPC_USART->LCR = 0x03;                     // DLAB = 0
}

char ua_inchar(void)	                         // look if there is a character available
{
    if (LPC_USART->LSR & 1)
        return LPC_USART->RBR & 0x7F;          // yes, return character from input buffer
    else
        return 0xFF;                           // no, return -1
}

char ua_getchar(void)                          // this function waits for a character
{
    while (!(LPC_USART->LSR & 0x1));
    return LPC_USART->RBR & 0x7F;              // Read character from input buffer
}

void ua_outchar(char c)		
{
    LPC_USART->THR = c;
    while(!(LPC_USART->LSR & 0x40));
}

void PrintByte(unsigned char b)
{
    ua_outchar(ascii[b >> 4]);
    ua_outchar(ascii[b & 0x0f]);
}

void PrintWord(unsigned short w)
{
    PrintByte((unsigned char)(w>>8));
    PrintByte((unsigned char)w);
}

//void PrintLong(long l)
//{
//    PrintWord((WORD)(l>>16));
//    PrintWord((WORD)l);
//}

void PrintBDecimal(unsigned char b)
{
  unsigned char p;

    p = ascii[b / 10];
    if (p != '0')
        ua_outchar(p);
    ua_outchar(ascii[b % 10]);
}

void PrintWDecimal(unsigned short w)
{
    ua_outchar(ascii[w / 10000]);
    w %= 10000;
    ua_outchar(ascii[w / 1000]);
    w %= 1000;
    ua_outchar(ascii[w / 100]);
    w %= 100;
    ua_outchar(ascii[w / 10]);
    ua_outchar(ascii[w % 10]);
}

void PrintString(const char *s)
{
    while (*s)
    {
        if (*s == '\n')
            ua_outchar('\r');                  // output a '\r' first
        ua_outchar(*s);
        s++;
    }
}
