stm32f103c8t6usart3的代码
时间: 2023-10-26 14:05:56 浏览: 83
好的,以下是一个简单的示例代码,实现了通过USART3发送字符串和接收字符串的功能:
```c
#include "stm32f10x.h"
#include <stdio.h>
void USART3_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
// 使能USART3和GPIOB时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
// 配置USART3的GPIO引脚
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; // USART3_TX
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11; // USART3_RX
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOB, &GPIO_InitStructure);
// 配置USART3
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(USART3, &USART_InitStructure);
// 使能USART3
USART_Cmd(USART3, ENABLE);
}
void USART3_SendString(char* str)
{
while (*str)
{
while (USART_GetFlagStatus(USART3, USART_FLAG_TXE) == RESET);
USART_SendData(USART3, *str++);
}
}
void USART3_ReceiveString(char* str, uint32_t max_len)
{
uint32_t i = 0;
char c;
while (i < max_len - 1)
{
while (USART_GetFlagStatus(USART3, USART_FLAG_RXNE) == RESET);
c = USART_ReceiveData(USART3);
if (c == '\r' || c == '\n')
{
break;
}
str[i++] = c;
}
str[i] = '\0';
}
int main(void)
{
char buf[100];
USART3_Init();
while (1)
{
USART3_SendString("Please enter a string:\r\n");
USART3_ReceiveString(buf, sizeof(buf));
USART3_SendString("You entered: ");
USART3_SendString(buf);
USART3_SendString("\r\n");
}
}
```
阅读全文