GPIO+TIM(无PWM)实现呼吸灯功能

程序特点:

1、模块化,可快速移植,5分钟便可完成移植。

2、通过GPIO+普通定时器,实现呼吸灯功能。

3、PWM周期为5ms,占空比调节时间为20ms,占空比为100等份,即呼吸灯从暗到亮需要20ms*100=2s。

4、可以通过更改参数来更改占空比等份数和呼吸灯周期。

BreathLed.c

#include "Breathled.h"

Breath_LED Breathled;

void Breath_Led_Init()
{
	Breathled.EN=0;
	Breathled.DIR=1;
	Breathled.pwm_cnt=0;
	Breathled.stall=0;
	Breathled.pwm_period=100;
	Breathled.pwm_duty=0;
	Breathled.cnt=0;
}

void Breath_Led_Driver()//放在50us中断
{
	if(!Breathled.EN)
		return;
	if(Breathled.pwm_cnt<Breathled.pwm_period)//50*100=5ms
		Breathled.pwm_cnt++;
	else
	{
		Breathled.pwm_cnt=0;
		if(Breathled.stall<4)//5ms*4=20ms
			Breathled.stall++;
		else
		{
			Breathled.stall=0;
			if(Breathled.DIR)
			{
				if(Breathled.pwm_duty<Breathled.pwm_period)//20ms*100=2s
					Breathled.pwm_duty++;
				else
				{
					Breathled.EN=0;
					Breathled.DIR=0;
				}
			}
			else
			{
				if(Breathled.pwm_duty)
					Breathled.pwm_duty--;
				else
				{
					Breathled.EN=0;
					Breathled.DIR=1;
				}
			}
		}
	}		
	if(Breathled.pwm_cnt<Breathled.pwm_duty)
		Set_ALL_LED_ON();
	else
		Set_ALL_LED_OFF();
}


BreathLed.h

#ifndef BREATHLED_H
#define BREATHLED_H
struct Breath_LED
{
	byte EN	:1;
	byte DIR:1;
	byte pwm_cnt;
	byte pwm_duty;
	byte pwm_period;
	byte stall;
	byte cnt;
};

extern Breath_LED Breathled;

#endif

tim.c

#include "tim.h"

void TIM2_Init()
{
	tm2ct = 0;					
	tm2b = 200;				
	$ TM2C SYSCLK,Disable,Period;						
	$ TM2S 8BIT,/1,/1;
	INTEN.TM2 = 1;
	INTRQ.TM2 = 0;
}

main.c

#include "tim.h"
#include "Breathled.h"

int main(void)
{
    TIM2_Init();
    Breath_Led_Init();
    Breathled.EN=1;//呼吸灯从暗到亮,然后全亮并停止呼吸。
    while()
    {
        
    }
}

void Interrupt (void)
{
    pushaf;
	if(Intrq.TM2)//50us
	{
		Intrq.TM2=0;
		Breath_Led_Driver();	
	}
    popaf;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值