#include "iocc2530.h"
#define LED1 P1_1
#define sw1 P0_1
unsigned char h = 0;
unsigned char flag = 0;
unsigned char a=1; //a = 1渐亮,a=2渐灭
//初始化
void Init()
{
P1SEL &= ~0x02; //11100000
P1DIR |= 0x02; //00011011
LED1=1;
P0SEL &=~0X02;//按键
P0DIR |=0X02;
PERCFG=0x40; //定时器1选择外设位置2
T1CCTL1=0x64; //定时器1通道2向上比较,比较模式
T1CC1L=0xff; //0~255 0000 1111
T1CC1H=h;
}
void delay(int n)
{
int s = 1000;
int i = 0;
for(i = 0;i < n;i++)
while(s--);
}
void ss() //呼吸灯
{
if((T1STAT&0x02)>0)
{
T1STAT=T1STAT&0xfd; //清除中断标志
if(a==1) //渐亮
h=h+1;
else //渐灭
h=h-1;
T1CC1L=0xff; //重装比较值
T1CC1H=h;
if(h>=254) //最大亮度
a=2; //设为渐灭
if(h==0) //最小亮度
a=1; //设为渐亮
}
}
void scan_key()
{
if(sw1 == 0)
{
delay(2);
if(sw1 == 0)
{
while(sw1==0);//等待按键松开
if(flag == 0) //第一次按下
{
flag = 1;
T1CTL |= 0x01;//定时器1时钟频率1分频,自由运行模式
P1SEL|=0x02; //设置灯的引脚为外设功能
}
else //第二次按下
{
flag = 0;
T1CTL &=~0X03;//关闭定时器
P1SEL &=~0X02;//灯的引脚设置为普通IO
LED1 = 1;
}
}
}
}
void main()
{
Init();
while(1)
{
scan_key();
if(flag)
{
ss();
}
}
}
通过按键控制呼吸灯的开启和关闭,需要注意的是,灯设置为外设功能时,直接熄灭等不起作用。因此熄灭灯之前需要将灯的初始化改为普通IO。