Page MenuHomec4science

uart.c
No OneTemporary

File Metadata

Created
Tue, Dec 3, 06:15
#include "uart.h"
#define UARTXy(x,y) U ## x ## y
#define INIT_UARTX(x,interrupt_number,mode,brgval) do{\
UARTXy(x,MODEbits).STSEL = 0;/* 1 stop bit */\
UARTXy(x,MODEbits).PDSEL = 0;/* No parity 8 bits*/\
UARTXy(x,MODEbits).ABAUD = 0; /* Auto-baud Disabled*/ \
UARTXy(x,MODEbits).BRGH = (char)mode;\
UARTXy(x,BRG) = brgval;\
/* Interrupt every char for Rx and TX */\
UARTXy(x,STAbits).UTXISEL0 = 0;\
UARTXy(x,STAbits).UTXISEL1 = 0;\
UARTXy(x,STAbits).URXISEL0 = 0;\
UARTXy(x,STAbits).URXISEL1 = 0;\
/* disable all interrupt callbacks, handled by DMA*/\
IEC ## interrupt_number ## bits.UARTXy(x,TXIE) = 0;\
IEC ## interrupt_number ## bits.UARTXy(x,RXIE) = 0;\
/*enable tx and rx */\
UARTXy(x,MODEbits).UARTEN = 1;\
UARTXy(x,STAbits).UTXEN = 1;\
}while(0)
#define abs(a) ((a) <= 0 ? -(a) : (a) )
void init_uart_for_sbcp(uart_device dev,
unsigned long baudrate,
unsigned long clock_frequency){
unsigned int i;
//compute all possible baudrate values that can be generated by the dsPIC33
char desired_mode[4] = {
0, //low speed
0, //low speed
1, //high speed
1 //high speed
};
long desired_brgval[4] = {
clock_frequency / (16 * baudrate) + 1, //round down
clock_frequency / (16 * baudrate), //round up
clock_frequency / (4 * baudrate) + 1, //round down
clock_frequency / (4 * baudrate) //round up
};
unsigned int best_index = -1;
long smaller_error = 1000;
for(i = 0 ; i < 4; ++i){
long actual_baudrate = clock_frequency / ((desired_mode[i] == 0 ? 16 : 4) * (desired_brgval[i] + 1));
long error = 1000* abs(baudrate - actual_baudrate) / baudrate;
if(error < smaller_error ){
smaller_error = error;
best_index = i;
}
}
if(smaller_error >= 30){ //more than 3% of error
return;
}
if(dev == UART_1){
INIT_UARTX(1,0,desired_mode[best_index],desired_brgval[best_index]);
} else if(dev == UART_2){
INIT_UARTX(2,1,desired_mode[best_index],desired_brgval[best_index]);
} else {
return;
}
}
void uart_map_rx_input(uart_device dev, rp_pin_t pin){
if(dev == UART_1){
_U1RXR = pin;
} else {
_U2RXR = pin;
}
}
void uart_map_cts_input(uart_device dev, rp_pin_t pin){
if(dev == UART_1){
_U1CTSR = pin;
} else {
_U2CTSR = pin;
}
}

Event Timeline