蓝桥杯 小蜜蜂 单元训练08:外部中断的基本操作
#include "stc15f2k60s2.h"
#define LED(x) \
{ \
P0 = x; \
P2 = P2 & 0x1f | 0x80; \
P2 &= 0x1f; \
}
#define L1 0xFE; // 定义L1亮灯
#define L8 0x7F; // 定义L8亮灯
sbit KeyS5 = P3 ^ 2; // 定义S5
typedef unsigned int uin8_t;
uin8_t interruptEnalbe = 0;
uin8_t workingStatus = 0;
uin8_t timerCounter = 0;
uin8_t timerSecCounter = 0;
uin8_t timerEnable = 0;
uin8_t timerSecEnable = 0;
void Working()
{
switch (workingStatus)
{
case 0:
LED(P0 & L1); // L1灯亮
if (timerEnable) // 灯闪烁需要时间间隔
workingStatus = 1;
timerEnable = 0;
break;
case 1:
LED(P0 | 0x01); // L1灯灭
if (timerEnable)
workingStatus = 0;
timerEnable = 0;
break;
default:
workingStatus = 0;
break;
}
}
void LightLed8()
{
LED(P0 & L8); // L8亮灯,同时不影响L1
}
void OffLed8()
{
if (timerSecEnable)
{
LED(P0 | 0x80); // L8熄灭,同时不影响L1
timerSecEnable = 0;
}
}
void Timer0_Init(void) // 1毫秒@12.000MHz
{
AUXR |= 0x80; // 定时器时钟1T模式
TMOD &= 0xF0; // 设置定时器模式
TL0 = 0x20; // 设置定时初始值
TH0 = 0xD1; // 设置定时初始值
TF0 = 0; // 清除TF0标志
TR0 = 1; // 定时器0开始计时
ET0 = 1; // 使能定时器0中断
EA = 1;
}
void INT0_init()
{
IT0 = 1; // 上升沿还是下降沿
EX0 = 1; // 使能打开
EA = 1; // 全局使能打开
}
void main()
{
LED(0xff);
INT0_init();
Timer0_Init();
while (1)
{
if (interruptEnalbe)
{
Working();
OffLed8();
}
}
}
void INT0_ISR() interrupt 0
{
if (KeyS5 == 0)
{
interruptEnalbe = 1;
LightLed8(); // 这个可以写到外面,比如增加Led8Proc()函数,将LightLe8与OffLed8作为子函数调用。
}
else
interruptEnalbe = 0;
}
void Timer0_Isr(void) interrupt 1
{
if (++timerCounter == 50) // 50ms
{
timerCounter = 0;
timerEnable = 1;
if (++timerSecCounter == 60) // 3000ms ,3s
{
timerSecCounter = 0;
timerSecEnable = 1;
}
}
}