写一个stm32f103c8t6的串口数据发送
时间: 2023-05-28 12:02:06 浏览: 115
以下是一个基本的STM32F103C8T6串口数据发送代码示例:
```c
#include "stm32f10x.h"
void USART2_Init(void);
void USART2_SendChar(char c);
void USART2_SendString(char* s);
int main(void)
{
USART2_Init();
USART2_SendString("Hello, world!\r\n");
while (1);
return 0;
}
void USART2_Init(void)
{
// Enable GPIOA, USART2, AFIO clocks
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO | RCC_APB1Periph_USART2, ENABLE);
// Configure USART2 Tx (PA2) as alternative function push-pull
GPIO_InitTypeDef GPIO_InitStructure;
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 (PA3) as input floating
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// Configure USART2
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);
// Enable USART2
USART_Cmd(USART2, ENABLE);
}
void USART2_SendChar(char c)
{
// Wait until Tx buffer empty
while (USART_GetFlagStatus(USART2, USART_FLAG_TXE) == RESET);
// Send character
USART_SendData(USART2, c);
}
void USART2_SendString(char* s)
{
while (*s != '\0')
{
USART2_SendChar(*s++);
}
}
```
这个代码中,在main函数中我们调用了USART2_Init()初始化串口,并通过USART2_SendString()发送了一条字符串。USART2_SendChar()是用来发送单个字符的函数,可以结合使用来发送字符串。在这个示例中,我们使用了PB12和PB13作为UART2的TX和RX引脚,波特率是115200。你可以根据你的具体需求修改这些参数。