最近要用多个串口,MINI stm32 好像共有3个,看着usart3被TFT给占了,就用了usart2(没有考虑端口重映射),根据原子哥的usart——init改编的
注意usart2是属于APB1上的外设,最大时钟36MHZ,建议大家从SystemInit();一层层往下看看,了解系统启动时钟配置很关键,最后确保
/* PCLK1 = HCLK */ //对应APB1外设,并且最大36MHZ,故DIV 2
RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE1_DIV2;(对应defined SYSCLK_FREQ_72MHz)
void uart2_init(u32 bound)
{
//GPIO端口设置
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
USART_DeInit(USART2);
//USART2_TX PA.2
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
//USART2_RX PA.3
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
//Usart2 NVIC 配置
NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3 ;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 4; //
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道使能
NVIC_Init(&NVIC_InitStructure); //根据NVIC_InitStruct中指定的参数初始化外设NVIC寄存器USART2
//USART 初始化设置
USART_InitStructure.USART_BaudRate = bound;//一般设置为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(USART2, &USART_InitStructure);
USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);//开启中断
USART_Cmd(USART2, ENABLE); //使能串口
}
要在led,或者uart1初始化之后再调用这个,因为如红 {MOD}部分只使能了usart2时钟,要配置TX P02 RX P03引脚,之前要保证PORTA时钟使能
简单测试程序:
void bsp_cmd_send(u8 *cmd_data)
{
u8 i;
for(i=0;i<10;i++)
{
USART_SendData(USART2,*(cmd_data++));
//delay_ms(1);
while(USART_GetFlagStatus(USART2,USART_FLAG_TC)!=SET);//等待发送结束
}
}
u8 cmd_get_in[10]={0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a};
void USART2_IRQHandler(void) //串口2中断服务程序
{
u8 Res;
if(USART_GetITStatus(USART2, USART_IT_RXNE) != RESET) //接收中断
{
Res =USART_ReceiveData(USART2);//(USART1->DR); //读取接收到的数据
}
}
void uart2_test(void)
{
//bsp_init();
bsp_cmd_send(cmd_get_in);
}
友情提示: 此问题已得到解决,问题已经关闭,关闭后问题禁止继续编辑,回答。
---------------------------------
解决了,原因及解决办法,楼上已经贴出
一周热门 更多>