01-02GPIO-LED闪灯实验
一、
硬件准备:
- 1块STM32F103C8T6最小系统板
- 1个ST-LINK V2烧录器
- 若干杜邦线
运用:
- 板载LED灯-引脚PC13
延时函数Delay.h
点击查看代码
#ifndef _DELAY_H_
#define _DELAY_H_
#include "stm32f10x.h" // Device header
void Delay_us(uint32_t us);
void Delay_ms(uint32_t ms);
void Delay_s(uint32_t s);
#endif
延时函数Delay.c
点击查看代码
#include "Delay.h"
/**
* @brief 微秒级延时
* @param xus 延时时长,范围:0~233015
* @retval 无
*/
void Delay_us(uint32_t xus)
{
SysTick->LOAD = 72 * xus; //设置定时器重装值
SysTick->VAL = 0x00; //清空当前计数值
SysTick->CTRL = 0x00000005; //设置时钟源为HCLK,启动定时器
while(!(SysTick->CTRL & 0x00010000)); //等待计数到0
SysTick->CTRL = 0x00000004; //关闭定时器
}
/**
* @brief 毫秒级延时
* @param xms 延时时长,范围:0~4294967295
* @retval 无
*/
void Delay_ms(uint32_t xms)
{
while(xms--)
{
Delay_us(1000);
}
}
/**
* @brief 秒级延时
* @param xs 延时时长,范围:0~4294967295
* @retval 无
*/
void Delay_s(uint32_t xs)
{
while(xs--)
{
Delay_ms(1000);
}
}
LED.h
点击查看代码
#ifndef __LED_H
#define __LED_H
#include "stm32f10x.h" // Device header
// PC13 LED配置
#define LED_PIN GPIO_Pin_13
#define LED_PORT GPIOC
#define LED_CLK RCC_APB2Periph_GPIOC
void LED_Init(void); //函数声明
void LED_Toggle(void); //LED翻转函数:切换LED的亮/灭状态
void LED_Blink(uint32_t times); //控制LED闪烁指定次数
#endif
LED.c
点击查看代码
#include "LED.h"
#include "Delay.h"
#include "stm32f10x.h" // Device header
void LED_Init(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC,ENABLE); //开启GPIOC的时钟
GPIO_InitTypeDef GPIO_InitStructure; //定义一个GPIO_InitTypeDef类型的结构体变量
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13; //选择要使用的I/O引脚,此处选择PC13引脚
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //设置引脚输出模式为推挽输出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //设置引脚的输出速度为50MHz
GPIO_Init(GPIOC,&GPIO_InitStructure); //调用初始化库函数初始化GPIOC端口
GPIO_WriteBit(GPIOC, GPIO_Pin_13, Bit_RESET);
}
// 1. LED 状态翻转函数:切换LED的亮/灭状态
void LED_Toggle(void)
{
// 读取当前LED对应引脚的输出状态(Bit_SET=高电平,Bit_RESET=低电平)
if(GPIO_ReadOutputDataBit(LED_PORT, LED_PIN) == Bit_SET)
{
// 若当前为高电平 → 置为低电平(LED点亮,需结合硬件连接判断)
GPIO_ResetBits(LED_PORT, LED_PIN);
}
else
{
// 若当前为低电平 → 置为高电平(LED熄灭,需结合硬件连接判断)
GPIO_SetBits(LED_PORT, LED_PIN);
}
}
/**
* @brief 控制LED闪烁指定次数
* @param times: 闪烁次数(1次闪烁 = 亮200ms + 灭200ms)
* @retval 无
*/
void LED_Blink(uint32_t times)
{
// 循环times次,实现指定次数闪烁
for(uint32_t i = 0; i < times; i++)
{
GPIO_ResetBits(LED_PORT, LED_PIN); // LED点亮(低电平)
Delay_ms(200); // 延时200ms(保持点亮状态)
GPIO_SetBits(LED_PORT, LED_PIN); // LED熄灭(高电平)
Delay_ms(200); // 延时200ms(保持熄灭状态)
}
}
主函数main.c
点击查看代码
#include "stm32f10x.h"
#include "LED.h"
#include "Delay.h"
int main(void)
{
LED_Init();
while(1)
{
// //1、使得PC13LED灯亮
// GPIO_WriteBit(GPIOC, GPIO_Pin_13,Bit_RESET); //写0
//
// //2、使得PC13LED灯灭
// GPIO_WriteBit(GPIOC, GPIO_Pin_13, Bit_SET); //写1
//
// //3、使得LED灯交替500ms亮灭闪烁
// GPIO_WriteBit(GPIOC, GPIO_Pin_13,Bit_RESET); //写0
// Delay_ms(500);
// GPIO_WriteBit(GPIOC, GPIO_Pin_13, Bit_SET); //写1
// Delay_ms(500);
//
// //4、亮灭翻转
// LED_Toggle();
// Delay_ms(500);
//
// //5、闪烁(亮200ms灭200ms循环3次,灭2s)
// LED_Blink(3);
// Delay_s(2);
}
}

浙公网安备 33010602011771号