void usartinit()
{
USART_InitTypeDef USART_InitStructure;
USART_StructInit(&USART_InitStructure);
// USART_ClockInitTypeDef USART_ClockInitStructure;//定义串口模式初始化结构体
RCC_APB2PeriphClockCmd( RCC_APB2Periph_USART1,ENABLE);
/*
USART_ClockInitStructure.USART_Clock = USART_Clock_Enable;//
USART_ClockInitStructure.USART_CPOL = USART_CPOL_Low;
USART_ClockInitStructure.USART_CPHA = USART_CPHA_2Edge;
USART_ClockInitStructure.USART_LastBit = USART_LastBit_Disable;
USART_ClockInit(USART1,&USART_ClockInitStructure);
*/
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;
/* Configure USART1 */
USART_Init(USART1, &USART_InitStructure);
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
USART_ITConfig(USART1, USART_IT_TXE, ENABLE);
/* Enable the USART1 */
USART_Cmd(USART1, ENABLE);
}
void NVIC_Configuration(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
/* Configure the NVIC Preemption Priority Bits */
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);
/* Enable the USART1 Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQChannel;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
另外 USART_ClearFlag(USART1,USART_FLAG_TC);初始化要把这一步加上
中断服务程序
void USART1_IRQHandler(void)
{
if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)
{
USART_SendData(USART1, 'a'); //发送一位数据
GPIO_SetBits(GPIOC,GPIO_Pin_7);
USART_ClearITPendingBit(USART1, USART_IT_RXNE);
USART_ITConfig(USART1, USART_IT_TXE, ENABLE);
}
if(USART_GetITStatus(USART1, USART_IT_TXE) != RESET)
{
USART_SendData(USART1, 'b');
USART_ITConfig(USART1, USART_IT_TXE, DISABLE);
}
}
最后切记在stm32f10X_it.c文件下加上#include "stm32f10x_usart.h" 不然无法调用串口函数 好了
注意好这些,你的串口就能通讯了,如果还不行请回复
|