stm32f407串口发送到DR
时间: 2023-09-04 11:10:41 浏览: 43
在 STM32F407 上,当你想要通过串口发送数据时,需要将数据写入到 USART 的 Data Register (DR) 中。下面是一个基本的示例代码:
```
#include "stm32f4xx.h"
void USART2_Init(void) {
// 使能 GPIOA 和 USART2 的时钟
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
// 配置 PA2 和 PA3 作为 USART2 的 TX 和 RX 引脚
GPIO_PinAFConfig(GPIOA, GPIO_PinSource2, GPIO_AF_USART2);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource3, GPIO_AF_USART2);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2 | GPIO_Pin_3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// 配置 USART2
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_Tx;
USART_Init(USART2, &USART_InitStructure);
// 使能 USART2
USART_Cmd(USART2, ENABLE);
}
void USART2_SendChar(uint8_t ch) {
// 等待 USART2 的发送缓冲区为空
while (USART_GetFlagStatus(USART2, USART_FLAG_TXE) == RESET);
// 将数据写入到 USART2 的 Data Register (DR) 中,发送数据
USART_SendData(USART2, (uint16_t)ch);
}
int main(void) {
USART2_Init();
// 发送单个字符 'A'
USART2_SendChar('A');
while (1);
}
```
以上代码中,`USART2_Init()` 函数用于初始化 USART2 的 GPIO 和 USART2 的参数配置;`USART2_SendChar()` 函数用于向 USART2 发送单个字符;`main()` 函数中初始化 USART2 并使用 `USART2_SendChar()` 函数发送了单个字符 'A'。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)