随便写的,下载到板子上试了试没问题,1分钟 5分钟时间太长,我改成5秒 25秒,你只要改下数字就行.
#include <reg52.h>
sbit relay = P1^0; //继电器,0线圈吸合,1线圈断开
sbit key = P1^1; //按键,0为按下,1为松开
unsigned char key_timer_cnt; //检测按键计时变量
unsigned int relay_timer_cnt; //继电器吸合断开计时变量
unsigned char relay_timer_cnt_min; //继电器延迟断开计数器分钟,因为5分钟,1ms为单位将超过65535
unsigned char relay_state; //记录继电器状态 0=未触发 1=待吸合 2=待断开
void Init_T0(void) //定时器中断初始化,设置为1ms
{
TMOD = 0x01;
TH0 = 0xfc;
TL0 = 0x18;
EA = 1;
ET0 = 1;
TR0 = 1;
}
void main(void)
{
Init_T0();
relay = 1; //断开继电器
relay_state = 0; //继电器处于未触发状态
while(1)
{
//想实现其他功能,再这里添加代码
}
}
void T0_ISR() interrupt 1 //1毫秒
{
TH0 = 0xfc;
TL0 = 0x18;
//***************************待触发状态,需要做的只是判断按键有没有按下*******************
if(relay_state == 0) //当继电器处于待触发状态
{
if(key == 0) //按键按下,并且继电器处于未触发状态
{
key_timer_cnt++; //按键计时器自加,用于消抖
if(key_timer_cnt>=5) //按键超过5毫秒
{
key_timer_cnt = 0;
relay_state = 1; //将继电器设成待吸合状态
}
}else
{
key_timer_cnt = 0;
}
}
//********************待吸合状态,等计数器加满就行*****************************
if(relay_state == 1)
{
relay_timer_cnt++;
if(relay_timer_cnt>=5000) //将5000改为60000 即为1分钟
{
relay = 0; //继电器吸合
relay_state = 2; //吸合后将状态转成待断开
relay_timer_cnt = 0;
}
}
//******************待断开状态,跟待吸合一样加满就行*******************************
if(relay_state == 2)
{
relay_timer_cnt++;
if(relay_timer_cnt>=5000) //将5000改为60000即为1分钟
{
relay_timer_cnt = 0;
relay_timer_cnt_min++; //每60秒加1
if(relay_timer_cnt_min>=5) //当分钟数等于5
{
relay = 1; //断开继电器
relay_timer_cnt_min = 0;
relay_timer_cnt = 0;
relay_state = 0; //断开后将继电器状态转换成未触发
}
}
}
} |