B板子的串口2初始化代码:
[mw_shl_code=c,true]/**
* @brief: USART2 初始化
* @param: baud: 波特率
*/[/mw_shl_code]
[mw_shl_code=c,true]// 波特率:115200
void usart2_init(u32 baud)
{
float temp;
u16 mantissa;
u16 fraction;
u32 pclk2;
pclk2=RCC_ClocksStatus.PCLK2_Frequency;
temp=(float)pclk2/(baud*16); //得到USARTDIV
mantissa=temp; //得到整数部分
fraction=(temp-mantissa)*16; //得到小数部分
mantissa<<=4;
mantissa+=fraction;
RCC->APB2ENR|=1<<2; //使能PORTA口时钟
RCC->APB1ENR|=1<<17; //使能串口2时钟
RCC->APB2ENR|=1<<0;// hzh test
GPIOA->CRL &= 0XFFFF00FF;
GPIOA->CRL |= 0X00008B00;//IO状态设置
RCC->APB1RSTR|=1<<17; //复位串口2
RCC->APB1RSTR&=~(1<<17);//停止复位
//波特率设置
USART2->BRR=mantissa; // 波特率设置
USART2->CR1|=0X200C; //1位停止,无校验位.
#ifdef EN_USART1_RX //如果使能了接收
//使能接收中断
USART2->CR1|=1<<8; //PE中断使能
USART2->CR1|=1<<5; //接收缓冲区非空中断使能
//USART2->CR2 |= 0x0200;
//USART2->CR2 |= 1<<4;
My_NVIC_Init(3,3,USART2_IRQChannel,5);//组5,最低优先级
//My_NVIC_Init(1,0,USART2_IRQChannel,2);//组5,最低优先级
#endif
}
[/mw_shl_code]
B板子的串口2接收中断:
[mw_shl_code=c,true]//串口2中断服务程序
u8 Usart2RxBuf[USART1_BUF_SIZE];//USART1串口数据缓冲区
u8 Usart2RxStat=0; //接收状态
//接收状态
//bit7,接收完成标志
//bit6,接收到0x0d
//bit5~0,接收到的有效字节数目
/**
* @brief: 串口中断服务程序
*/
void USART2_IRQHandler(void)
{
u8 res;
if(USART2->SR&(1<<5))//接收到数据
{
res=USART2->DR;
if((Usart2RxStat&0x80)==0)//接收未完成
{
if(Usart2RxStat&0x40)//接收到了0x0d
{
if(res!=0x0a)
{
Usart2RxStat=0;//接收错误,重新开始
}
else
{
Usart2RxStat|=0x80; //接收完成了
}
}else //还没收到0X0D
{
if(res==0x0d)
{
Usart2RxStat|=0x40;
}
else
{
Usart2RxBuf[Usart2RxStat&0X3F]=res;
Usart2RxStat++;
if(Usart2RxStat>63)
{
Usart2RxStat=0;//接收数据错误,重新开始接收
}
}
}
}
}
}
[/mw_shl_code]
A板子的串口2初始化代码(是调用系统函数初始化的):
[mw_shl_code=c,true]USART_InitStructure.USART_BaudRate = 115200;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_Init(USART2, &USART_InitStructure);
USART2->CR1 |= 0x0020;
USART_Cmd(USART2, ENABLE); [/mw_shl_code]
A板子GPIO口初始化代码:
[mw_shl_code=c,true]/*uart2*/
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3 ;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure); [/mw_shl_code]
A板子的发送代码,也是调用的系统函数:
[mw_shl_code=c,true]Print(COM2,"Hello World!\r\n");[/mw_shl_code]
目前的现象是:A板子的串口向PC机发送的数据,用串口工具能正确看到,但是向B板子的串口2发送的数据,B板子的收到的数据是乱码,完全不是自己想要的数据,所以就导致中断里的接收缓冲区一直收不到回车换行,所以缓冲区就一直溢出-->清零,
我是初学者,代码写的乱,不要见怪,还请大家帮帮忙,先谢谢了!!! |