#include <p33Fxxxx.h>
_FOSCSEL(FNOSC_PRIPLL); // Primary (XT, HS, EC) Oscillator with PLL
_FOSC(FCKSM_CSDCMD & OSCIOFNC_OFF & POSCMD_HS);
// Clock Switching and Fail Safe Clock Monitor is disabled
// OSC2 Pin Function: OSC2 is Clock Output
// Primary Oscillator Mode: EC, External
_FWDT(FWDTEN_OFF); // Watchdog Timer Enabled/disabled by user software
// (LPRC can be disabled by clearing SWDTEN bit in RCON register
void ini232(void);
void __attribute__((__interrupt__)) _U2RXInterrupt(void); /*Declare 232 interrupt ISRs*/
unsigned char rxdata1; //定义接收数据缓存变量
//******************主函数*************************
int main (void)
{
unsigned char i;
ini232(); //调用RS232口初始化函数
for(i=100;i>0;i--); //延长时间以保证可靠初始化
while(1);
}
//*************RS232初始化函数**********************
void ini232(void)
{
// Fin=10M
// Fosc= Fin*M/(N1*N2), Fcy=Fosc/2
// Fosc= 10*24/(2*2)=60
// Fcy, Instruction Clock = Fosc/2 = 30MHz
PLLFBD=22; // M=24
CLKDIVbits.PLLPOST=0; // N1=2
CLKDIVbits.PLLPRE=0; // N2=2
// Disable Watch Dog Timer
RCONbits.SWDTEN=0;
// Wait for PLL to lock
while(OSCCONbits.LOCK!=1) {};
TRISDbits.TRISD2 =0;
TRISFbits.TRISF2 =1; //RC脚输入
TRISFbits.TRISF3 =1; //TX脚输出
// IPC6bits.U2RXIP=7; //中断优先级别
IEC0bits.U1TXIE=0; //禁止发送中断
IEC0bits.U1RXIE=1; //使能接收中断
U1BRG =110; //27; //波特率设置为19200
U1MODE =0x8800; //使能UART功能
U1STA=0X0000;
U1STAbits.UTXEN =1; //允许发送
}
//************接收中断函数**************************
void __attribute__((__interrupt__)) _U1RXInterrupt(void)
{
IFS0bits.U1RXIF = 0; //清除中断标志位
while(U1STAbits.URXDA) //读取接收到的所有数据
{
rxdata1=U1RXREG; //缓存接收的数据
if(rxdata1==0x55) PORTDbits.RD2 =1;
U1TXREG=rxdata1& 0xFF; //把接收到的数据发送回去
// U2TXREG=0x55;
while(U1STAbits.TRMT==0); //等待发送完毕
}
}
发表评论 取消回复