使用标准库,编写stm32f103c8t6通过USART2串口输出数值的程序
时间: 2023-08-12 13:04:04 浏览: 30
以下是一个使用标准库在stm32f103c8t6上通过USART2串口输出数值的程序:
```c
#include "stm32f10x.h"
#include <stdio.h>
void USART2_Init(void);
void USART2_Write(char data);
int main(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
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);
USART2_Init();
while(1)
{
int num = 1234;
char buffer[10];
sprintf(buffer, "%d", num);
for(int i=0; i<10; i++)
{
if(buffer[i] == '\0')
break;
USART2_Write(buffer[i]);
}
USART2_Write('\n');
delay_ms(1000);
}
}
void USART2_Init(void)
{
USART_InitTypeDef USART_InitStructure;
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_Write(char data)
{
while(USART_GetFlagStatus(USART2, USART_FLAG_TXE) == RESET);
USART_SendData(USART2, data);
}
void delay_ms(uint32_t ms)
{
for(uint32_t i=0; i<ms; i++)
{
for(uint32_t j=0; j<72000; j++);
}
}
```
这个程序使用了USART2串口,波特率为115200,每秒输出一个数字1234,每个数字输出后会换行,然后等待1秒钟再输出下一个数字。注意,这个程序只输出数字,如果你想输出字符串或者其他类型的数据,需要使用不同的函数,例如sprintf()函数可以将数字转换为字符串。