使用标准库,编写stm32f103c8t6通过USART2串口打印的程序,上一个不能用
时间: 2024-05-12 10:14:58 浏览: 66
基于stm32f103c8t6实现的串口命令行程序
5星 · 资源好评率100%
以下是使用标准库,在stm32f103c8t6上通过USART2串口打印的程序。
```c
#include "stm32f10x.h"
#include <stdio.h>
void USART2_Init(void);
void USART2_SendChar(char ch);
void USART2_SendString(char* str);
int main(void)
{
USART2_Init();
while (1)
{
USART2_SendString("Hello, world!\r\n");
}
}
void USART2_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO | RCC_APB2Periph_USART1, ENABLE);
// Configure USART2 Tx (PA.2) as alternate function push-pull
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// Configure USART2 Rx (PA.3) as input floating
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// USART2 configuration
USART_InitStructure.USART_BaudRate = 115200;
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);
// Enable USART2
USART_Cmd(USART2, ENABLE);
}
void USART2_SendChar(char ch)
{
while (USART_GetFlagStatus(USART2, USART_FLAG_TXE) == RESET);
USART_SendData(USART2, ch);
}
void USART2_SendString(char* str)
{
while (*str)
{
USART2_SendChar(*str++);
}
}
```
这个程序使用了USART2串口和PA2和PA3引脚。在main函数中,我们初始化了USART2,并在while循环中不断发送"Hello, world!\r\n"字符串。USART2_Init函数用于配置USART2,USART2_SendChar和USART2_SendString函数用于发送单个字符和字符串。
阅读全文