51单片机利用P3.3接一个外部中断输入,控制8个LED灯循环点亮
时间: 2023-07-18 12:34:54 浏览: 82
好的,这个问题涉及到51单片机的外部中断和IO口控制,我会尽力回答。
首先,我们需要在程序中配置外部中断和IO口,具体的代码如下:
```c
#include <reg51.h>
sbit LED1 = P1^0;
sbit LED2 = P1^1;
sbit LED3 = P1^2;
sbit LED4 = P1^3;
sbit LED5 = P1^4;
sbit LED6 = P1^5;
sbit LED7 = P1^6;
sbit LED8 = P1^7;
void ExternalInterrupt_Init()
{
EA = 1; // 开启中断总开关
EX0 = 1; // 开启外部中断0
IT0 = 1; // 配置外部中断0为下降沿触发方式
}
void main()
{
ExternalInterrupt_Init();
while(1)
{
LED1 = 1;
delay(1000);
LED2 = 1;
delay(1000);
LED3 = 1;
delay(1000);
LED4 = 1;
delay(1000);
LED5 = 1;
delay(1000);
LED6 = 1;
delay(1000);
LED7 = 1;
delay(1000);
LED8 = 1;
delay(1000);
LED1 = 0;
LED2 = 0;
LED3 = 0;
LED4 = 0;
LED5 = 0;
LED6 = 0;
LED7 = 0;
LED8 = 0;
delay(1000);
}
}
void ExternalInterrupt0_ISR() interrupt 0
{
LED1 = 1;
LED2 = 1;
LED3 = 1;
LED4 = 1;
LED5 = 1;
LED6 = 1;
LED7 = 1;
LED8 = 1;
delay(1000);
LED1 = 0;
LED2 = 0;
LED3 = 0;
LED4 = 0;
LED5 = 0;
LED6 = 0;
LED7 = 0;
LED8 = 0;
delay(1000);
}
```
在这份代码中,我们首先定义了8个LED灯对应的IO口,然后在 `ExternalInterrupt_Init()` 函数中配置了外部中断和中断触发方式。
在 `main()` 函数中,我们通过循环点亮8个LED灯,每个灯持续1秒钟。同时,我们等待外部中断的触发,当外部中断触发时,会自动进入 `ExternalInterrupt0_ISR()` 函数中,这个函数会让8个LED灯同时点亮1秒钟,然后熄灭1秒钟,然后回到 `main()` 函数中继续循环点亮8个LED灯。
需要注意的是,我们在程序中使用了 `delay()` 函数,这个函数需要自行实现。我这里提供一个简单的实现方式:
```c
void delay(unsigned int ms)
{
unsigned int i, j;
for(i = 0; i < ms; i++)
for(j = 0; j < 125; j++);
}
```
这个函数的作用是让程序暂停指定的毫秒数,具体时间可以根据需要自行调整。
希望这个回答能够帮到你!