呼吸燈是指亮度逐漸變亮和變暗的過程,通過控制LED亮和滅的時(shí)間長(zhǎng)短
< 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實(shí)現(xiàn)函數(shù)*********************
#include "led.h"
void LED_Init(void){ //LED初始化函數(shù)
GPIO_InitTypeDef GPIO_InitStructure; //IO口結(jié)構(gòu)體聲明
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_GPIOB|RCC_APB2Periph_GPIOC,ENABLE); // 啟動(dòng)IO端口,因?yàn)镮O端口是在APB2上,所以要啟動(dòng)APB2
GPIO_InitStructure.GPIO_Pin = LED1 | LED2; //選擇端口號(hào)
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //IO的接口工作方式 此為推挽輸出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //IO口的接口速度2/10/50MHz 只有輸出時(shí)才設(shè)置
GPIO_Init(LEDPORT, &GPIO_InitStructure); //選擇設(shè)置的IO端口組
}
<delay.h>********************延時(shí)函數(shù)頭文件************************
#ifndef __DELAY_H
#define __DELAY_H
void delay_s(u16 s);//u16 16位無符號(hào)變量
void delay_ms(u16 ms);
void delay_us(u32 us);//u32 32位無符號(hào)變量
#endif
<delay.c>********************延時(shí)函數(shù)執(zhí)行************************
#include "delay.h"
#define AHB_INPUT 72
void delay_us(u32 uS){ //us延時(shí)程序
SysTick->LOAD=AHB_INPUT*uS; SysTick->VAL=0x00; SysTick->CTRL=0x00000005;
while(! (SysTick->CTRL&0x00010000));
SysTick->CTRL=0x00000004;
}
void delay_ms(u16 ms){ //us延時(shí)程序
while( ms-- != 0){
delay_us(1000); }
}
void delay_s(u16 s){ // s延時(shí)程序
while( s-- != 0){
delay_ms(1000);
}
}
<main.c>*******************主函數(shù)**************************
#include "stm32f10x.h" //STM32頭文件
#include "delay.h"
#include "led.h"
int main (void){
u8 MENU;//狀態(tài)菜單 當(dāng)MENU為0 時(shí),表示逐漸變亮的狀態(tài);當(dāng)MENU為1時(shí),表示逐漸變暗的狀態(tài);u8表示無符號(hào) 8位變量
u16 t,i;//u16表示無符號(hào) 16 位變量
RCC_Configuration(); //時(shí)鐘設(shè)置
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); //延時(shí)t us
GPIO_WriteBit(LEDPORT,LED1,(BitAction)(0)); //LED1滅
delay_us(501-t); //延時(shí)501-t us
}
t++;
if(t==500){//t加到500,改變狀態(tài)值MENU
MENU = 1;
}
}
if(MENU == 1){ //LED逐漸變暗
for(i = 0; i < 10; i++){
GPIO_WriteBit(LEDPORT,LED1,(BitAction)(1)); //LED1亮
delay_us(t); //延時(shí)t
GPIO_WriteBit(LEDPORT,LED1,(BitAction)(0)); //LED1滅
delay_us(501-t); //延時(shí)501-t
}
t--;
if(t==1){
MENU = 0;
}
}
}
}