使用标准库,编写stm32f103c8t6通过USART2串口输出数值的程序
时间: 2023-12-18 20:53:50 浏览: 23
下面是一个使用标准库的STM32F103C8T6通过USART2串口输出数值的程序:
```c
#include "stm32f10x.h"
#include <stdio.h>
void USART2_Init(void);
void USART2_WriteChar(char ch);
void USART2_WriteString(char* str);
void USART2_WriteInt(int num);
int main(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
USART2_Init();
int num = 12345;
char buffer[16];
sprintf(buffer, "%d", num);
USART2_WriteString("The number is: ");
USART2_WriteString(buffer);
USART2_WriteChar('\n');
while(1)
{
}
}
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 as alternate function push-pull */
GPIO_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);
/* Configure USART2 Rx 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_Tx;
USART_Init(USART2, &USART_InitStructure);
USART_Cmd(USART2, ENABLE);
}
void USART2_WriteChar(char ch)
{
while(!(USART2->SR & USART_FLAG_TXE));
USART2->DR = (ch & 0xFF);
}
void USART2_WriteString(char* str)
{
int i = 0;
while(str[i])
{
USART2_WriteChar(str[i]);
i++;
}
}
void USART2_WriteInt(int num)
{
char buffer[16];
sprintf(buffer, "%d", num);
USART2_WriteString(buffer);
}
```
在这个例子中,我们使用了USART2串口输出一个整数值。在main函数中,我们将数值12345存储在一个int类型的变量中,并使用sprintf函数将其格式化为一个字符串。然后,我们使用USART2_WriteString函数将字符串"The number is: "发送到串口,接着使用USART2_WriteString函数将格式化后的整数值字符串发送到串口,最后使用USART2_WriteChar函数将换行符发送到串口,使输出更加清晰可读。
USART2_Init函数用于初始化USART2串口。首先,我们使用RCC_APB2PeriphClockCmd函数启用GPIOA、AFIO和USART2时钟。然后,我们配置PA2引脚(USART2的Tx引脚)为复用功能推挽输出,并将PA3引脚(USART2的Rx引脚)配置为浮空输入。接着,我们配置USART2的波特率、数据位、停止位、奇偶校验和硬件流控制,最后启用USART2。
USART2_WriteChar函数用于将一个字符发送到USART2串口。它首先检查USART_SR寄存器的TXE标志来确保USART2准备好发送数据。然后,它将字符写入USART_DR寄存器,该寄存器将数据传输到USART2的Tx引脚上。
USART2_WriteString函数用于将一个字符串发送到USART2串口。它遍历字符串中的每个字符,并将每个字符都发送到USART2串口。
USART2_WriteInt函数用于将一个整数值发送到USART2串口。它首先使用sprintf函数将整数值格式化为一个字符串,然后使用USART2_WriteString函数将该字符串发送到USART2串口。