#include <plib.h> // Peripheral Library
#include "stdio.h"
// External oscillator frequency
#define SYSCLK 80000000UL // (8MHz Crystal/ FPLLIDIV * FPLLMUL / FPLLODIV)
#define GetSystemClock() (SYSCLK)
#define GetPeripheralClock() (GetSystemClock()/(1 << OSCCONbits.PBDIV))
// initialize UART
// Input: baud rate
// Output: 1 for OK, 0 if baud rate error > 3%
int UART2Init(const long int BAUDRATE)
{
int error;
// This initialization assumes 36MHz Fpb clock. If it changes,
// you will have to modify baud rate initializer.
UARTConfigure(UART2, UART_ENABLE_PINS_TX_RX_ONLY);
UARTSetFifoMode(UART2, UART_INTERRUPT_ON_TX_NOT_FULL | UART_INTERRUPT_ON_RX_NOT_EMPTY);
UARTSetLineControl(UART2, UART_DATA_SIZE_8_BITS | UART_PARITY_NONE | UART_STOP_BITS_1);
UARTSetDataRate(UART2, GetPeripheralClock(), BAUDRATE);
UARTEnable(UART2, UART_ENABLE_FLAGS(UART_PERIPHERAL | UART_RX | UART_TX));
error = (int) (100 *( (long int) UARTGetDataRate(UART2, GetPeripheralClock())- BAUDRATE)/BAUDRATE);
if (error > 2)
{ printf("\n\n" UARTNAME " baud rate shold be %ld is %lu error %d\n", BAUDRATE, UARTGetDataRate(UART2, GetPeripheralClock()), error); return -1; }
printf(""UARTNAME " baud rate %ld set up\n", BAUDRATE);
return 0;
}
//Function:UART GetChar : waits for a byte to be received. It then returns that byte.
char UART2GetChar()
{
return UARTGetDataByte(UART2); // read character into buffer
}
// Function:UART PutChar - This routine writes a character to the transmit FIFO
void UART2PutChar(const char ch )
{
while(!UARTTransmitterIsReady(UART2));
UARTSendDataByte(UART2, ch); // transmit character
}