呼吸灯是指亮度逐渐变亮和变暗的过程,通过控制LED亮和灭的时间长短
< led.h>**********************LED头文件***********************
#ifndef __LED_H
#define __LED_H
#define LEDPORT GPIOB //宏定义
#define LED1 GPIO_Pin_0
#define LED2 GPIO_Pin_1
void LED_Init(void);
#endif
< led.c>************************LED实现函数*********************
#include "led.h"
void LED_Init(void){ //LED初始化函数
GPIO_InitTypeDef GPIO_InitStructure; //IO口结构体声明
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_GPIOB|RCC_APB2Periph_GPIOC,ENABLE); // 启动IO端口,因为IO端口是在APB2上,所以要启动APB2
GPIO_InitStructure.GPIO_Pin = LED1 | LED2; //选择端口号
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //IO的接口工作方式 此为推挽输出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //IO口的接口速度2/10/50MHz 只有输出时才设置
GPIO_Init(LEDPORT, &GPIO_InitStructure); //选择设置的IO端口组
}
<delay.h>********************延时函数头文件************************
#ifndef __DELAY_H
#define __DELAY_H
void delay_s(u16 s);//u16 16位无符号变量
void delay_ms(u16 ms);
void delay_us(u32 us);//u32 32位无符号变量
#endif
<delay.c>********************延时函数执行************************
#include "delay.h"
#define AHB_INPUT 72
void delay_us(u32 uS){ //us延时程序
SysTick->LOAD=AHB_INPUT*uS; SysTick->VAL=0x00; SysTick->CTRL=0x00000005;
while(! (SysTick->CTRL&0x00010000));
SysTick->CTRL=0x00000004;
}
void delay_ms(u16 ms){ //us延时程序
while( ms-- != 0){
delay_us(1000); }
}
void delay_s(u16 s){ // s延时程序
while( s-- != 0){
delay_ms(1000);
}
}
<main.c>*******************主函数**************************
#include "stm32f10x.h" //STM32头文件
#include "delay.h"
#include "led.h"
int main (void){
u8 MENU;//状态菜单 当MENU为0 时,表示逐渐变亮的状态;当MENU为1时,表示逐渐变暗的状态;u8表示无符号 8位变量
u16 t,i;//u16表示无符号 16 位变量
RCC_Configuration(); //时钟设置
LED_Init();//LED初始化
while(1){
if(MENU == 0){ //LED逐渐变亮
for(i = 0; i < 10; i++){
GPIO_WriteBit(LEDPORT,LED1,(BitAction)(1)); //LED1亮 delay_us(t); //延时t us
GPIO_WriteBit(LEDPORT,LED1,(BitAction)(0)); //LED1灭
delay_us(501-t); //延时501-t us
}
t++;
if(t==500){//t加到500,改变状态值MENU
MENU = 1;
}
}
if(MENU == 1){ //LED逐渐变暗
for(i = 0; i < 10; i++){
GPIO_WriteBit(LEDPORT,LED1,(BitAction)(1)); //LED1亮
delay_us(t); //延时t
GPIO_WriteBit(LEDPORT,LED1,(BitAction)(0)); //LED1灭
delay_us(501-t); //延时501-t
}
t--;
if(t==1){
MENU = 0;
}
}
}
}