//==========PIC18F46K80的串口初始化函数
void USART_Init()//============URAST设置
{
//============================
TRISC6 = 0; //TX
TRISC7 = 1; //RX
//WPUC7 = 0; //关闭弱上拉
//============================
//TXSTAx:发送状态和控制寄存器
TXSTAbits.BRGH = 0; //0= 选择低速波特率 1= 高速
TXSTAbits.TX9 = 0; //选择8位数据位
TXSTAbits.TXEN = 1; //使能发送
RCSTAbits.SPEN = 1; //串口已启用
RCSTAbits.RX9 = 0; //选择8位数据位
RCSTAbits.CREN = 1; //使能接收
//计算SPBRGL和SPBRGH的基础上,所需的波特率值
//对于8位异步模式与BRGH = 0:目标波特率= FOSC/64([SPBRGH:SPBRGL] +1)
//对于8位异步模式,BRGH = 1:目标波特率= FOSC/16([SPBRGH:SPBRGL] +1)
//BRGH = 0,FOSC = 16MHz 波特率 = 9600
// 9600 = FOSC/64([SPBRGH:SPBRGL] +1)
// 9600 = FOSC/64(X +1)
// 9600 = Fosc/64X + 64
// 9600(64X + 64)= FOSC
// X = [FOSC /(9600)(64)] -1
// X = [16000000 /(9600)(64)] -1
// X = SPBRGH:SPBRGL = 25.01(四舍五入至25)
//SPBRGL = 207; //16MHz = 1200bps,32MHz = 2400bps //= 207.33 (四舍五入至207 )
//SPBRGL = 103; //16MHz = 2400bps,32MHz = 4800bps //= 103.16 (四舍五入至103 )
//SPBRGL = 51; //这里是计算值SPBRGH和SPBRGL的 //16MHz = 4800bps,32MHz = 9600bps //= 51.08 (四舍五入至51 )
//SPBRGL = 25; //这里是计算值SPBRGH和SPBRGL的 //16MHz = 9600bps,32MHz = 19200bps //= 25.04(四舍五入至25)
//SPBRGL = 12; //16MHz = 19200bps,32MHz = 38400bps //= 12.02(四舍五入至12)
//波特率设置程序
EE_read_UART_bps(); //读出UART口波特率
if(EE_UART_bps == 1) //16MHz = 1200bps
{
SPBRG1 = 207;
}
else if(EE_UART_bps == 2) //16MHz = 2400bps
{
SPBRG1 = 103;
}
else if(EE_UART_bps == 3) //16MHz = 4800bps
{
SPBRG1 = 51;
}
else if(EE_UART_bps == 4) //16MHz = 9600bps
{
SPBRG1 = 25;
}
else if(EE_UART_bps == 5) //16MHz = 19200bps
{
SPBRG1 = 12;
}
else
{
SPBRG1 = 25; //默认9600bps
}
SPBRGH1 = 0;
PIR1bits.RCIF = 0; //接收中断标志0
PIE1bits.RCIE = 1; //使能UART接收中断
INTCONbits.PEIE = 1; //允许外设中断
INTCONbits.GIE = 1; //使能全局中断
}