/*
© [2024] Microchip Technology Inc. and its subsidiaries.

    Subject to your compliance with these terms, you may use Microchip 
    software and any derivatives exclusively with Microchip products. 
    You are responsible for complying with 3rd party license terms  
    applicable to your use of 3rd party software (including open source  
    software) that may accompany Microchip software. SOFTWARE IS ?AS IS.? 
    NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS 
    SOFTWARE, INCLUDING ANY IMPLIED WARRANTIES OF NON-INFRINGEMENT,  
    MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT 
    WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, 
    INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY 
    KIND WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF 
    MICROCHIP HAS BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE 
    FORESEEABLE. TO THE FULLEST EXTENT ALLOWED BY LAW, MICROCHIP?S 
    TOTAL LIABILITY ON ALL CLAIMS RELATED TO THE SOFTWARE WILL NOT 
    EXCEED AMOUNT OF FEES, IF ANY, YOU PAID DIRECTLY TO MICROCHIP FOR 
    THIS SOFTWARE.
*/

#include "../uart2.h"

#define SUCCESS 0xAA;
#define FAILURE 0x55;

void UART2_Initialize(void)
{
/*    
     Set the UART2 module to the options selected in the user interface.
     Make sure to set LAT bit corresponding to TxPin as high before UART initialization
*/
    // MODE Asynchronous 8-bit UART; RXEN ; TXEN ; ABDEN ; BRGS ; SENDB ; BRKOVR ; RXBIMD ; WUE ; SIDL ; ON disabled; FLO ; TXPOL ; C0EN ; STP 1 Stop bit sent, 1 checked at RX; RXPOL ; RUNOVF ; HALFDPLX ; CLKSEL Standard Speed Peripheral Clock; CLKMOD enabled; ACTIVE ; SLPEN ; 
    U2CON = 0x8000000UL;
    // TXCIF ; RXFOIF ; RXBKIF ; CERIF ; ABDOVIF ; TXCIE ; RXFOIE ; RXBKIE ; FERIE ; CERIE ; ABDOVIE ; PERIE ; TXMTIE ; STPMD ; TXWRE ; RXWM ; TXWM ; 
    U2STAT = 0x2E0080UL;
    // BaudRate 9599.69; Frequency 100000000 Hz; BRG 10417; 
    U2BRG = 0x28B1UL;
    
//    U2STATbits.TXMTIE = 1;
    U2CONbits.ON = 1;   // enabling UART ON bit
    U2CONbits.TXEN = 1;
    U2CONbits.RXEN = 1;
}
void UART2_Write(uint8_t txData)
{
    while(U2STATbits.TXBF == 1)
    {
        
    }

    U2TXB = txData;    // Write the data byte to the USART.
}
int __attribute__((__section__(".libc.write"))) write(int handle, void *buffer, unsigned int len) 
{
    unsigned int i;

    for (i = len; i; --i)
    {
        UART2_Write(*(char*)buffer++);
    }
    return(len);
}
/* New API added for Diagnostics */
uint16_t UART2_Transmit(uint8_t *buffer, uint16_t size)
{
	unsigned int txsize = 0;
	//loop until transmitting all the bytes is complete
	while(txsize < size)
	{
		//Fill the U2TXREG with the data
		U2TXB = buffer[txsize++];
		//Wait one instruction cycle after filling data in the U2TXREG
		Nop();
		//Wait until the data is transmitted
		while(U2STATbits.TXMTIF != 1);
	}
    return SUCCESS;
}