老實了,我把程序改了一下讓計數器做最簡單的計數工作。
#include <REGX51.H>
void Delay(int ms);
void Timer0_Init(void);
void UpdateLED(void);
char LED = 0;
bit direction = 0;
bit auto_mode = 0;
unsigned int counter = 0; // 將計數器移出中斷
void main()
{
P2 = 0xFF;
Timer0_Init();
while(1)
{
if(P3_0 == 0)
{
Delay(5);
if(P3_0 == 0)
{
while(P3_0 == 0);
Delay(5);
if(direction != 0) // 如果當前方向不同,只改變方向
{
direction = 0;
}
auto_mode = 1;
}
}
if(P3_1 == 0)
{
Delay(5);
if(P3_1 == 0)
{
while(P3_1 == 0);
Delay(5);
if(direction != 1) // 如果當前方向不同,只改變方向
{
direction = 1;
}
auto_mode = 1;
}
}
// 主循環(huán)中處理LED更新
if(counter >= 10)
{
counter = 0;
if(auto_mode)
{
UpdateLED();
}
}
}
}
void Timer0_ISR(void) interrupt 1
{
TH0 = 0xB0;
TL0 = 0x18;
// 只做最簡單的計數工作
counter++;
}
void UpdateLED(void)
{
if(direction == 0) // 向右循環(huán)
{
LED++;
if(LED >= 8)
{
LED = 0;
}
}
else // 向左循環(huán)
{
if(LED == 0)
{
LED = 7; // 從0減到7,實現循環(huán)
}
else
{
LED--;
}
}
P2 = ~(0x01 << LED); // 更新LED顯示
}
void Timer0_Init(void)
{
TMOD &= 0xF0;
TMOD |= 0x01;
TH0 = 0xB0;
TL0 = 0x18;
ET0 = 1; //允許定時器0中斷
EA = 1; //開啟總中斷
TR0 = 1;
}
void Delay(int ms)
{
int i,j;
while(ms--)
{
for(i=1;i<=ms;i++)
for(j=1;j<=300;j++);
}
}
現在他加了一條要求。當中斷切換時,從當前燈切換循環(huán)點亮熄滅。我沒懂什么意思,這個意思是指關機后啟動燈還是在那個位置還是什么意思?
|