STM32 UART(接收 ,發(fā)送數(shù)據(jù))
掃描二維碼
隨時(shí)隨地手機(jī)看文章
UART接收發(fā)送數(shù)據(jù):
平臺(tái):STM32F401 discovery版
此代碼用的UART6,TX,RX對(duì)應(yīng)的PIN腳是PC6,PC7
如圖:
步驟一:初始化串口的GPIO,USART,并且配置上UART的RX中斷
voidUSART6_Config(void)
{
USART_InitTypeDefUSART_InitStructure;
NVIC_InitTypeDefNVIC_InitStructure;
GPIO_InitTypeDefGPIO_InitStructure;
/*EnableGPIOclock*/
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC,ENABLE);
/*EnableUSARTclock*/
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART6,ENABLE);
/*ConnectUSARTpinsto*/
GPIO_PinAFConfig(GPIOC,GPIO_PinSource6,GPIO_AF_USART6);
GPIO_PinAFConfig(GPIOC,GPIO_PinSource7,GPIO_AF_USART6);
/*ConfigureUSARTTxandRxasalternatefunctionpush-pull*/
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;//GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_OType=GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd=GPIO_PuPd_UP;
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_6;
GPIO_Init(GPIOC,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_7;
GPIO_Init(GPIOC,&GPIO_InitStructure);
/*USARTxconfiguration----------------------------------------------------*/
USART_InitStructure.USART_BaudRate=115200;//5250000;
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(USART6,&USART_InitStructure);
/*EnabletheUSARTxInterrupt*/
NVIC_InitStructure.NVIC_IRQChannel=USART6_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority=0;
NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE;
NVIC_Init(&NVIC_InitStructure);
USART_ITConfig(USART6,USART_IT_RXNE,ENABLE);
USART_Cmd(USART6,ENABLE);
}
步驟二:測(cè)試一下TX,即用printf,但是printf內(nèi)部是調(diào)用fputs,所以需要重定向一下
intfputc(intch,FILE*f)
{
USART_SendData(USART6,(unsignedchar)ch);
while(!(USART6->SR&USART_FLAG_TXE));
return(ch);
}
intfgetc(FILE*f)
{
while(USART_GetFlagStatus(USART6,USART_FLAG_RXNE)==RESET);
return(int)USART_ReceiveData(USART6);
}
步驟三:編寫RX中斷函數(shù)
[cpp]view plaincopy
voidUSART6_IRQHandler(void)
{
uint8_tch;
if(USART_GetITStatus(USART6,USART_IT_RXNE)!=RESET)
{
ch=USART_ReceiveData(USART6);
printf("%cn",ch);
}
}
注意地方:使用的IAR,沖定向的時(shí)候出現(xiàn)FILE類型找不到,可是在C原因中#include
追代碼發(fā)現(xiàn):
#if _DLIB_FILE_DESCRIPTOR
typedef _Filet FILE;
#endif /* _DLIB_FILE_DESCRIPTOR */
_DLIB_FILE_DESCRIPTOR宏是0,但是IAR又不讓修改,所以肯定是哪里的lib沒有配置,于是找到如圖就搞定了
附一張板子圖:
用標(biāo)準(zhǔn)的杜邦線連接
整個(gè)工程如連接:
http://download.csdn.net/detail/xiaoxiaopengbo/9425422