写一个stm32f103的串口发送代码
时间: 2023-12-07 12:05:45 浏览: 31
下面是一个简单的STM32F103串口发送代码示例:
```c
#include "stm32f10x.h"
void USART1_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
USART_InitTypeDef USART_InitStruct;
// 使能USART1和GPIOA时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, ENABLE);
// 配置USART1_TX引脚为推挽输出模式,最大速度为50MHz
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStruct);
// 配置USART1的工作参数
USART_InitStruct.USART_BaudRate = 9600;
USART_InitStruct.USART_WordLength = USART_WordLength_8b;
USART_InitStruct.USART_StopBits = USART_StopBits_1;
USART_InitStruct.USART_Parity = USART_Parity_No;
USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStruct.USART_Mode = USART_Mode_Tx;
USART_Init(USART1, &USART_InitStruct);
// 使能USART1
USART_Cmd(USART1, ENABLE);
}
void USART1_SendChar(char ch)
{
// 等待上一个数据发送完成
while (!(USART1->SR & USART_SR_TXE));
// 发送数据
USART1->DR = ch;
}
int main(void)
{
USART1_Init();
while (1)
{
// 发送Hello, World!
USART1_SendChar('H');
USART1_SendChar('e');
USART1_SendChar('l');
USART1_SendChar('l');
USART1_SendChar('o');
USART1_SendChar(',');
USART1_SendChar(' ');
USART1_SendChar('W');
USART1_SendChar('o');
USART1_SendChar('r');
USART1_SendChar('l');
USART1_SendChar('d');
USART1_SendChar('!');
USART1_SendChar('\n');
USART1_SendChar('\r');
}
}
```
以上代码中,`USART1_Init()`函数用于初始化USART1串口,配置GPIO和USART工作参数。`USART1_SendChar()`函数用于发送一个字符数据。在主函数中,通过调用`USART1_SendChar()`函数发送一串字符串数据。注意,在发送数据前需要等待上一个数据发送完成。
相关推荐
![](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)