STM32学习【2】STM32F103C8T6串口2USART2程序

来源:互联网 发布:mysql怎样导出数据库 编辑:程序博客网 时间:2024/04/30 03:39

       STM32F103C8T6串口1(PA10/RXD1,PA9/TXD1)用来烧写程序,串口2(PA3/RXD2,PA2/TXD2)接串口模块与电脑串口助手通信。IO口PA1接LED+470R电阻+D3V3。

       调试后,能正常运行的程序如下:


#include "stm32f10x.h"#include "stm32f10x_usart.h"#define LED_ON  GPIO_ResetBits(GPIOA ,GPIO_Pin_1)#define LED_OFF GPIO_SetBits(GPIOA ,GPIO_Pin_1)void GPIO_Config(void);void USART2_Config(void);void RCC_Config(void);void  Delay(u32 nCount){for(; nCount != 0; nCount--);}int main(void){RCC_Config();   //时钟设置GPIO_Config();USART2_Config();while(1){LED_OFF;Delay(0xfffff);Delay(0xfffff);Delay(0xfffff);Delay(0xfffff);Delay(0xfffff);Delay(0xfffff);USART_SendData(USART2,0x12);LED_ON;Delay(0xfffff);Delay(0xfffff);Delay(0xfffff);Delay(0xfffff);Delay(0xfffff);Delay(0xfffff);}}void RCC_Config(void){/*开启外设时钟*/RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA , ENABLE);RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);}void GPIO_Config(void){GPIO_InitTypeDef GPIO_InitStructure;  //定义一个结构体变量GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;   GPIO_Init(GPIOA, &GPIO_InitStructure); //初始化库函数//PA2 TXD2GPIO_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);//PA3 RXD2GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;   GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;   GPIO_Init(GPIOA, &GPIO_InitStructure); }void USART2_Config(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(USART2, &USART_InitStructure); USART_ITConfig(USART2, USART_IT_RXNE, ENABLE); //开启接收中断USART_ITConfig(USART2, USART_IT_TXE, ENABLE);//开启发送中断USART_Cmd(USART2, ENABLE);}

       程序编写过程中出现的问题:

       1、时钟设置函数void RCC_Config(void)中

       RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);

       若写成

       RCC_APB2PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);

       程序编译能够通过,但烧写后,程序无法正常运行。


       2、若没有配置串口USART2(PA3/RXD2,PA2/TXD2)对应IO口的输入输出模式,编译能够通过,但程序无法正常运行。

       PA2/TXD2应配置为

       GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;

       PA3/RXD2配置为

       GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;


       以上问题的具体解释都可以在STM32固件函数库用户手册找到。

       APB1时钟设置



       GPIO模式时钟设置



3 0
原创粉丝点击