#include "stm32f10x.h"
#include "delay.h"
#include "stdio.h"
#define USART2_REC_LEN 200
#define EN_USART2 1
#define Data_Head 0x59
#define Data_Length 9
u16 USART2_RX_BUF[USART2_REC_LEN];
u16 TFMINI_Distance;
void USART2_Init(u32 bound)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2,ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_3;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_2;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
USART_InitStructure.USART_BaudRate=bound;
USART_InitStructure.USART_HardwareFlowControl=USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode=USART_Mode_Rx |USART_Mode_Tx;
USART_InitStructure.USART_Parity=USART_Parity_No;
USART_InitStructure.USART_StopBits=USART_StopBits_1;
USART_InitStructure.USART_WordLength=USART_WordLength_8b;
USART_Init(USART2,&USART_InitStructure);
USART_ITConfig(USART2,USART_IT_RXNE,ENABLE);
USART_Cmd(USART2,ENABLE);
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);
NVIC_InitStructure.NVIC_IRQChannel=USART2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3;
NVIC_InitStructure.NVIC_IRQChannelSubPriority=3;
NVIC_Init(&NVIC_InitStructure);
}
void USART2_IRQHandler(void)
{
static u8 seri_count=0;
u16 check_sum=0;
u8 i;
static u8 flag;
if(USART_GetITStatus(USART2,USART_IT_RXNE) != RESET)
{
USART_ClearFlag(USART2, USART_FLAG_RXNE);
USART_ClearITPendingBit(USART2, USART_IT_RXNE);
if(USART_ReceiveData(USART2)==Data_Head)
{
flag=1;
}
if(flag)
{
USART2_RX_BUF[seri_count++]=USART_ReceiveData(USART2);
if(seri_count == Data_Length)
{
if(USART2_RX_BUF[0]==Data_Head && USART2_RX_BUF[1]==Data_Head)
{
for(i=0;i<Data_Length-1;i++)
{
check_sum+=USART2_RX_BUF[i];
}
if((check_sum & 0x00ff)==USART2_RX_BUF[8])
{
TFMINI_Distance=USART2_RX_BUF[2]+USART2_RX_BUF[3]*256;
printf("dist= %d
",TFMINI_Distance);
seri_count=0;
flag=0;
}
}
}
}
}
}
int main(void)
{
USART2_Init(115200);
//while(1);
}
友情提示: 此问题已得到解决,问题已经关闭,关闭后问题禁止继续编辑,回答。
就是想要串口接收测距传感器传过来的数据,数据前两位是帧头0x59,3和4是距离,5和6位是强度,最后一位校验位等于前面的数据加起来取低八位。能看看问题出在哪里吗,串口调试助手上一直重复出现乱码,所以我注释了一下while,结果还那样。新手求教,并不是很会
再使能串口一,重定向printf函数就可以了吗?其他有没有什么问题啊?
大哥不行啊,还是一直乱码,能不能帮忙给我改一改啊?十分感激
一周热门 更多>