// UART2.c - for PIC24.
#include "uart2.h"
#ifdef _RP0R
#include "pps.h"
#endif
#include <stdlib.h>
#include <stdio.h>
#define BRG_DIV2 16
#define BRGH2 0
// initialize UART
// Input: baud rate
// Output: 1 for OK, -1 if baud rate error > 2%
int UART2Init(const unsigned long int BAUDRATE)
{
unsigned long int BAUDRATEREG = (((SYSCLK/2)+(8ul*BAUDRATE))/BRG_DIV2/BAUDRATE-1);
unsigned long int BAUD_ACTUAL = ((SYSCLK/2)/BRG_DIV2/(BAUDRATEREG+1));
unsigned long int BAUD_ERROR = ((BAUD_ACTUAL > BAUDRATE) ? BAUD_ACTUAL-BAUDRATE : BAUDRATE-BAUD_ACTUAL);
unsigned long int BAUD_ERROR_PRECENT = ((BAUD_ERROR*100+BAUDRATE/2)/BAUDRATE);
__C30_UART=2; // if UART2 set for printf output to this UART
// reconfigure the I/O pins if required
#ifdef _RP0R
iPPSOutput(OUT_PIN_PPS_RP10, OUT_FN_PPS_U2TX); // TXD
iPPSInput (IN_FN_PPS_U2RX,IN_PIN_PPS_RP17); // RXD
#endif
U2BRG = BAUDRATEREG; // set up baudrate
U2MODE = 0; // clear mode register
U2MODEbits.BRGH = BRGH2; //divider is 16
U2STA = 0; // clear status
U2MODEbits.UARTEN = 1; // enable UART
U2STAbits.UTXEN = 1; // enable reansmit
_U2RXIF = 0; // clear interrupt flag
if (BAUD_ERROR_PRECENT > 2)
{ printf("UART2 baud rate %lu error %lu%%\n", BAUDRATE, BAUD_ERROR_PRECENT); return -1; }
printf("UART2 baud rate %lu set up\n", BAUDRATE);
return 1;
}
//Function:UART CharReady - return true if there is a new byte in UART reception buffer.
char UART2CharReady()
{
return _U2RXIF; // none zero if UART has received data
}
//Function:UART GetChar : waits for a byte to be received. It then returns that byte.
char UART2GetChar()
{
while(! _U2RXIF); // wait for data
_U2RXIF = 0; // clear interrupt flag
return U2RXREG;
}
// Function:UART GetString - read a string until \n received or length reached
void UART2GetString(char *str , int length)
{
char ch=0;
while(ch != '\n')
if(UART2CharReady())
{
ch=*str=UART2GetChar();
str++;
*str=0;
if(--length<1) return;
}
}
// Function:UART PutChar - This routine writes a character to the transmit FIFO
void UART2PutChar(const char ch )
{
while(U2STAbits.TRMT == 0); // wait for transmit ready
U2TXREG = ch; // transmit character
}
//Function:UART PrintString - prints a string of characters to the UART.
void UART2PrintString(const char *str )
{
char c;
while( (c = *str++) )
UART2PutChar(c);
}