使用标准库,编写stm32f103c8t6通过USART2串口接收和输出数值的程序
时间: 2023-08-12 13:04:01 浏览: 96
基于STM32的USART串口通信程序
4星 · 用户满意度95%
好的,这里给你提供一个示例程序,使用USART2串口接收和输出数值:
```c
#include "stm32f10x.h"
#include <stdio.h>
#include <string.h>
void USART2_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
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);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_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_Rx | USART_Mode_Tx;
USART_Init(USART2, &USART_InitStructure);
USART_Cmd(USART2, ENABLE);
}
int main(void)
{
USART2_Init();
char buf[16];
uint16_t value = 0;
while (1)
{
if (USART_GetFlagStatus(USART2, USART_FLAG_RXNE) == SET)
{
char ch = USART_ReceiveData(USART2);
if (ch >= '0' && ch <= '9')
{
value = value * 10 + (ch - '0');
}
else if (ch == '\r' || ch == '\n')
{
sprintf(buf, "Received: %d\r\n", value);
int len = strlen(buf);
for (int i = 0; i < len; i++)
USART_SendData(USART2, buf[i]);
value = 0;
}
}
}
}
```
这个程序使用USART2串口接收和输出数值,波特率为115200。当接收到数字串时,将其转换为整数并输出;当接收到回车或换行符时,输出接收到的数字。注意,本程序只是一个示例,实际应用中需要根据具体情况进行修改。
阅读全文