13.25.6 Auto-Baud Code Example
dsPIC® DSC Auto-Baud Example is a dsPIC® DSC code example using the auto-baud function.
dsPIC® DSC Auto-Baud Example
//#define FCY 70000000UL
#define TypBaudrate 9600uL
#define U1BRG_BAUDRATE (FCY/(16 * TypBaudrate)) - 1
#define U1BRG_BAUD_MIN ((((FCY/(16 * TypBaudrate)) - 1)*1.07f)) // plus 7%
#define U1BRG_BAUD_MAX ((((FCY/(16 * TypBaudrate)) - 1)*0.93f)) // minus 7%
#define U1BRG_BREAK (FCY/(16 * 7880uL)) - 1 //7880 baud-rate is midpoint of required break
//window for MCP8021
//set up Oscillator_Initialize code here
void UART1_Init(void){
//UART configuration - set up PPS connections and UART module enable here
_TRISC12 = 1; //required for proper UART RX receiption of DE2 messages
_CNPUC12 = 1; //required to pull DE2 high because interconnect is open-drain
_ODC12 = 1; //recommended so pull-up is fully utilized
//PPS assignment of UART RX/TX to RC12
//enable half-duplex mode if available to auto-disable transmiter when idle
U1MODEbits.UARTEN = 1; //enable UART
U1MODEbits.URXEN = 1; //for half-duplex communication, keep RX on always and manage TX as
//needed in auto-baud routine
//if half-duplex mode not available, activate TXEN for transmission and disable TXEN when idle
__delay_ms(10); //10mS delay required after POR of MCP8021 and before requesting auto-baud
}
void UART1_AutoBaud(void){
U1MODEbits.UTXEN = 1; //Transmit enabled, UxTX pin controlled by UARTx.
U1BRG = U1BRG_BREAK; //7880baud representing 1.65ms dominant with 13bit BREAK
U1MODEbits.UTXBRK = 1; //Send BREAK command
U1TXREG = 0x00; //Dummy write to start BREAK command
while(U1STAHbits.URXBE == 0){ //wait for transmission to end then read out RXREG to
//avoid collision.
unsigned short dummy = U1RXREG;
}
U1MODEbits.UTXEN = 0; //disable TX while waiting on 0x55 from MCP8021
U1MODEbits.ABAUD = 1; //start the ABAUD counter upon receipt of next byte (0x55)
while(U1MODEbits.ABAUD); //application should handle timeout if auto-baud does not
complete and attempt auto-baud routine again
__delay_ms(3); //minimum delay of 2mS required after auto-baud complete
to allow for baud rate verification by host
//verify new baud clock is within limits of MCP8021 min and max baud-rate
if ((U1BRG > U1BRG_BAUD_MAX) && (U1BRG < U1BRG_BAUD_MIN)){
//success, use new baud-rate generator value
}
else{
//auto-baud out of range, reload last known good BRG value and attempt auto-baud routine again
}
}
