STM32F103C8T6串口2USART2程序
时间: 2023-10-20 21:07:02 浏览: 111
STM32串口USART2程序
以下是 STM32F103C8T6串口2USART2程序的代码:
```c
#include "stm32f10x.h"
void USART2_Init(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);
USART_InitTypeDef USART_InitStructure;
USART_InitStructure.USART_BaudRate = 9600;
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_SendChar(char ch)
{
while (USART_GetFlagStatus(USART2, USART_FLAG_TXE) == RESET);
USART_SendData(USART2, ch);
}
void USART2_SendString(char* str)
{
while (*str)
{
USART2_SendChar(*str++);
}
}
int main(void)
{
USART2_Init();
USART2_SendString("Hello World!");
while (1);
return 0;
}
```
以上代码实现了 STM32F103C8T6 的串口2(USART2)初始化和发送字符串功能。其中,`USART2_Init()` 函数用于初始化串口,`USART2_SendChar()` 函数用于发送单个字符,`USART2_SendString()` 函数用于发送字符串。
阅读全文