/*
 * uart.c
 *
 *  Created on: 15 Mar 2022
 *      Author: pika
 */

#include "uart.h"
#ifdef __USE_CMSIS
#include "LPC17xx.h"
#endif



void uart_init(uint32_t baudrate){
	LPC_SC->PCLKSEL0 &= ~(3<<6);

	LPC_SC->PCLKSEL0 |= 1<<6;   // pclk set to 100 MHz

    LPC_PINCON->PINSEL0 |= (1<<4); //TXD0

    LPC_PINCON->PINSEL0 |= (1<<6); //RXD0


    uint32_t Fdiv = (UART_PCLK)/(16*baudrate);
    LPC_UART0->LCR = 0x83;
    LPC_UART0->DLM = (Fdiv>>8)&0xff;
    LPC_UART0->DLL = Fdiv&0xff;

    LPC_UART0->LCR = 0x3;
    LPC_UART0->FCR = 0x07|(2<<6);//(2<<6) to active RX trigger level
}

void uart_send(char* buff, uint32_t length){
	int tmp;
	while (length-- != 0 ){
		//LPC_UART0->THR = *buff++;
		while(((LPC_UART0->LSR)&(1<<5)) == 0);//stuck in while when U1THR contains valid data
		LPC_UART0->THR = *buff++;
		tmp = LPC_UART0->RBR;
		//LPC_GPIO2->FIOCLR = 0xff;
		//LPC_GPIO2->FIOSET = tmp;
	}

}

void uart_receive_command(char* chara){
	char* curr = chara;
    while(((LPC_UART0->LSR)&(1)) == 0);
    *curr = LPC_UART0->RBR;
	while(*curr != '\n'){
        if((*curr != '\n')) curr++;
        while(((LPC_UART0->LSR)&(1)) == 0);
        *curr = LPC_UART0->RBR;
    }
}

void uart_receive_data(uint8_t* chara, int size){
	//size parameter add while size != size_given
	uint8_t* curr = chara;
    //while(((LPC_UART0->LSR)&(1)) == 0);
    for(int i = 0; i < size/2; i++){
    	while(((LPC_UART0->LSR)&(1)) == 0);
    	curr[2*i] = LPC_UART0->RBR;
    	while(((LPC_UART0->LSR)&(1)) == 0);
        curr[2*i+1] = LPC_UART0->RBR;
        //while(((LPC_UART0->LSR)&(1)) == 0);
        //curr[2*i] = LPC_UART0->RBR;
    }
}
