实验目的: 使用 STM32 的串口来发送和接收数据
实验步骤:
- STM32 串口简介
- 硬件设计
- 软件设计
- 下载验证
1. 串口简介
miniSTM32 板载 1 个USB串口和1个RS232串口,实验将使用USB串口将信息打印到电脑上;
串口设置步骤:
- 串口时钟使能,GPIO 时钟使能(使能函数)
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1)
- 串口复位 (归初始化)
#define USART1 ((USART_TypeDef *) USART1_BASE)
void USART_DeInit(USART_TypeDef* USARTx);//串口复位,DeInit
USART_DeInit(USART1); //复位串口 1;用的是串口1
- GPIO 端口模式设置 (设置为复用功能对应的模式)
- 串口参数初始化 (波特率,停止位等)
#define __IO volatile /*!< defines 'read / write' permissions */
//volatile是一个类型修饰符(type specifier),就像我们熟悉的const一样,它是被设计用来修饰被不同线程访问和修改的变量;
//volatile的作用是作为指令关键字,确保本条指令不会因编译器的优化而省略,且要求每次直接读值;
void USART_Init(USART_TypeDef* USARTx, USART_InitTypeDef* USART_InitStruct);
typedef struct
{
__IO uint16_t SR;
uint16_t RESERVED0;
__IO uint16_t DR;
uint16_t RESERVED1;
__IO uint16_t BRR;
uint16_t RESERVED2;
__IO uint16_t CR1;
uint16_t RESERVED3;
__IO uint16_t CR2;
uint16_t RESERVED4;
__IO uint16_t CR3;
uint16_t RESERVED5;
__IO uint16_t GTPR;
uint16_t RESERVED6;
} USART_TypeDef;
typedef struct
{
uint32_t USART_BaudRate; /*!< This member configures the USART communication baud rate.
The baud rate is computed using the following formula:
- IntegerDivider = ((PCLKx) / (16 * (USART_InitStruct->USART_BaudRate)))
- FractionalDivider = ((IntegerDivider - ((u32) IntegerDivider)) * 16) + 0.5 */
uint16_t USART_WordLength; /*!< Specifies the number of data bits transmitted or received in a frame.
This parameter can be a value of @ref USART_Word_Length */
uint16_t USART_StopBits; /*!< Specifies the number of stop bits transmitted.
This parameter can be a value of @ref USART_Stop_Bits */
uint16_t USART_Parity; /*!< Specifies the parity mode.
This parameter can be a value of @ref USART_Parity
@note When parity is enabled, the computed parity is inserted
at the MSB position of the transmitted data (9th bit when
the word length is set to 9 data bits; 8th bit when the