51单片机主程序控制 PO 口数码管 循环显示 0~8:外中断0、外中断1 发生时分别在P2口、PI口依次显示 0~8。中断1设置为高优先级,中断0 设置为低优先级,通过实验可演示优先级及中断联套等内容。 用用c语言来编写
时间: 2023-06-10 21:03:33 浏览: 73
以下是C语言代码:
#include "reg51.h"
#define LED P0
sbit KEY1 = P2^0; // 外中断0,P2口,低优先级
sbit KEY2 = P3^2; // 外中断1,P3口,高优先级
unsigned char code DisplayTable[] = { // 表示0~9的数码管编码
0x3f, 0x06, 0x5b, 0x4f, 0x66,
0x6d, 0x7d, 0x07, 0x7f, 0x6f
};
void Delay(unsigned int t); // 延时函数
void Key1Handler(void) interrupt 0; // 外中断0中断处理函数
void Key2Handler(void) interrupt 2; // 外中断1中断处理函数
void main()
{
unsigned char num = 0; // 初始数码管显示0
LED = DisplayTable[num]; // 数码管显示0
EA = 1; // 开启总中断
EX0 = 1; // 开启外中断0,低优先级
IT0 = 1; // 外中断0触发方式为下降沿
EX1 = 1; // 开启外中断1,高优先级
IT1 = 1; // 外中断1触发方式为下降沿
while(1) // 主程序循环
{
num++; // 数码管显示数字加1
if(num > 8)
num = 0; // 数码管显示到8后回到0
LED = DisplayTable[num];
Delay(1000); // 延时1秒
}
}
void Delay(unsigned int t) // 延时函数
{
unsigned int i, j;
for(i = 0; i < t; i++)
for(j = 0; j < 123; j++);
}
void Key1Handler(void) interrupt 0 // 外中断0中断处理函数
{
unsigned char i;
for(i = 0; i <= 8; i++) // P2口依次显示0~8
{
LED = DisplayTable[i];
Delay(500); // 延时0.5秒
}
}
void Key2Handler(void) interrupt 2 // 外中断1中断处理函数
{
unsigned char i;
for(i = 0; i <= 8; i++) // P1口依次显示0~8
{
LED = DisplayTable[i];
Delay(500); // 延时0.5秒
}
}