用库函数写stm32串口点亮led的程序
时间: 2024-04-24 21:24:10 浏览: 20
以下是使用库函数在STM32上点亮LED的示例程序:
```c
#include "stm32f4xx.h"
void GPIO_Init(void);
void USART_Init(void);
int main(void)
{
GPIO_Init(); // 初始化GPIO引脚
USART_Init(); // 初始化串口
while (1)
{
// 发送字符串 "LED ON" 到串口
USART_SendString("LED ON\r\n");
// 点亮LED
GPIO_SetBits(GPIOA, GPIO_Pin_5);
// 延时
for (int i = 0; i < 1000000; i++);
// 发送字符串 "LED OFF" 到串口
USART_SendString("LED OFF\r\n");
// 关闭LED
GPIO_ResetBits(GPIOA, GPIO_Pin_5);
// 延时
for (int i = 0; i < 1000000; i++);
}
}
void GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
// 使能GPIOA时钟
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
// 配置GPIOA Pin5为推挽输出模式
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
void USART_Init(void)
{
USART_InitTypeDef USART_InitStructure;
// 使能USART2时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
// 配置USART2引脚
GPIO_PinAFConfig(GPIOA, GPIO_PinSource2, GPIO_AF_USART2); // USART2_TX
GPIO_PinAFConfig(GPIOA, GPIO_PinSource3, GPIO_AF_USART2); // USART2_RX
// 配置USART2参数
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_Rx | USART_Mode_Tx;
USART_Init(USART2, &USART_InitStructure);
// 使能USART2
USART_Cmd(USART2, ENABLE);
}
void USART_SendString(char* str)
{
while (*str)
{
// 等待发送缓冲区为空
while (!(USART2->SR & USART_FLAG_TXE));
// 发送数据到串口
USART_SendData(USART2, *str);
// 指向下一个字符
str++;
}
}
```
这个示例程序使用了库函数来初始化GPIO和USART,通过串口发送字符串,并控制GPIO引脚点亮LED。你需要根据具体的STM32芯片型号和引脚连接进行相应的配置和修改。