新聞中心

STM32串口通訊USART

作者: 時(shí)間:2016-11-27 來源:網(wǎng)絡(luò) 收藏


void UART1_Configuration(void)
{

USART_InitTypeDef USART_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;


USART_Init(USART1, &USART_InitStructure);


USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);



USART_Cmd(USART1, ENABLE);
}

發(fā)送一個(gè)字符

u8 Uart1_PutChar(u8 ch)
{

USART_SendData(USART1, (u8) ch);
while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET)
{
}
return ch;
}


發(fā)送一個(gè)字符串

void Uart1_PutString(u8* buf , u8 len)
{
for(u8 i=0;i{
Uart1_PutChar(*buf++);
}
}

如果UART使用中斷發(fā)送數(shù)據(jù) 則需要修改stm32f10x_it.c 中的串口中斷函數(shù) 并且需要修改void NVIC_Configuration(void)函數(shù)

在中斷里面的處理 原則上是需要簡(jiǎn)短和高效 下面的流程是 如果接收到255個(gè)字符或者接收到回車符 則關(guān)閉中斷 并且把標(biāo)志位UartHaveData 置1


void USART1_IRQHandler(void)
{
if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)
{

RxBuffer[ RxCounter ] = USART_ReceiveData(USART1);
if( RxCounter == 0xfe || == RxBuffer[ RxCounter ] )
{

USART_ITConfig(USART1, USART_IT_RXNE, DISABLE);
RxBuffer[ RxCounter ] =