2019-07-21 01:45发布
城南花已开 发表于 2019-5-8 21:22 大佬您好,是不是串口发送的数据必须是已知的,格式必须也是知道的,我看他那里必须得是有回车换行的,什 ...
最多设置5个标签!
这是我给别人写的一段串口代码你参考下
u8 USART1_In,USART1_Out;
u8 USART1_RX_BUF[100];
void uart_init()
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1|RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9|GPIO_Pin_10;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
USART_InitStructure.USART_BaudRate = 9600;
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;
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3 ;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
USART_Init(USART1, &USART_InitStructure);
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
USART_Cmd(USART1, ENABLE);
}
void USART1_IRQHandler(void)
{
if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)
{
USART_ClearITPendingBit(USART1,USART_IT_RXNE);
USART1_RX_BUF[USART1_In++] = USART_ReceiveData(USART1);
if(USART1_In>=100) USART1_In=0;
}
}
u8 GetData(void)
{
u8 data;
data=USART1_RX_BUF[USART1_Out++];
if(USART1_Out>=100) USART1_Out=0;
return data;
}
int main(void)
{
u8 value=0;
......
while(1)
{
if(USART1_Out!=USART1_In)
{
value=GetData();
//你的处理代码 value就是串口接收的数据
}
}
......
}
一周热门 更多>