利用單片機 AT89C51 的外部中斷 0 和中斷 1, I/O 口,對 LED 和數碼管分別進行控制。以實現按鍵 K0 時 LED 燈亮滅閃爍,按鍵 K1 時做 LED 左和右流水運動。無按鍵操作時偶數位數碼管顯示 0-F。
使用74LS373可以節省I/O口
74LS373簡介:
74LS373是三態輸出的八D鎖存器,共有54S373和74LS373兩種線路。373 的輸出端 Q0~Q7 可直接與總線相連。當鎖存允許端LE爲高電平時,Q 隨數據D而變,當LE爲低電平時,D 被鎖存在已建立的數據電平。
真值表:
電路原理圖:
代碼如下:有相關的註釋
#include <reg51.h>
#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
sbit a=P2^5; //LED控制
sbit b=P2^6; //數碼管賦值控制
sbit c=P2^7; //數碼管段選
sbit K0=P3^2;
sbit K1=P3^3;
char d,n;
char t;
//共陰極數碼管數字顯示錶
uchar table[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71};
// 對應顯示 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
void delay(uint z)
{
uint x,y;
for(x=z;x>0;x--)
{
for(y=110;y>0;y--);
}
}
void int0()interrupt 0 //外部中斷0
{
for(d=0;d<5;d++)
{
a=1; //LED賦值控制打開 因爲在中斷裏面操作,所以還需要在打開LED控制,讓鎖存器賦值
P1=0x00; //賦值
delay(500);
//a=1;
P1=0xFF;
delay(500);
}
}
void int1()interrupt 2 //外部中斷1
{
a=1; //開啓鎖存器控制LED
t=0x7F; //0111 1111
P1=t;
while(1)
{
for(n=0;n<7;n++)
{
P1=t; //初值 //0111 1111
delay(400);
t=_cror_(t,1); //右移
}
for(n=0;n<7;n++)
{
P1=t; //初值 //0111 1111
delay(400);
t=_crol_(t,1); //左移
}
}
}
void main()
{
a=1;
P1=0xff; //數碼管關閉
EA=1; //打開總中斷開關
EX0=1; //外部中斷允許位
EX1=1;//外部中斷允許位
PX0=1; //外部中斷0高優先級
IT0=0;//外部中斷0電平觸發方式,低電平有效
IT1=0;//外部中斷1電平觸發方式,低電平有效
c=1; //打開段選
P0=0x55; //選擇數碼管 2 4 6 8
c=0; //關閉段選
while(1)
{
for(n=0;n<16;n++)
{
b=1; //開啓數碼管賦值
P0=table[n]; // 賦值
b=0; //關閉賦值控制
delay(800);
}
}
}
結果展示無按鍵:
按下K0(外部中斷0):
按下K1(外部中斷1):
以上電路和代碼僅供參考學習。