用寄存器版本编写以下代码功能1:主程序中,用定时器2实现300ms跑马灯,跑马方式为:LED3&LED4->LED2&LED5->LED1&LED6->LED2&LED5->LED3&LED4.一直循环 功能2: 按下KEY1触发外部中断,中断服务为:LED0&LED1->LED2&LED3->LED4&LED5->LED6&LED7,切换间隔时间为200ms,循环3次,完成后返回断点位置。 功能3: 按下KEY3触发外部中断,中断服务为:LED0->LED7齐闪烁,闪烁间隔时间为400ms,闪烁5次,完成后返回断点位置。要求:KEY3中断能够抢占KEY1中断
时间: 2023-08-10 16:25:57 浏览: 109
好的,这是一个使用寄存器编写的嵌入式系统代码,实现了跑马灯、按键中断等多种功能,且 KEY3 中断可以抢占 KEY1 中断。以下是代码实现:
```c
#include <reg52.h>
sbit LED0 = P1 ^ 0;
sbit LED1 = P1 ^ 1;
sbit LED2 = P1 ^ 2;
sbit LED3 = P1 ^ 3;
sbit LED4 = P1 ^ 4;
sbit LED5 = P1 ^ 5;
sbit LED6 = P1 ^ 6;
sbit LED7 = P1 ^ 7;
sbit KEY1 = P3 ^ 2;
sbit KEY3 = P3 ^ 4;
unsigned char LED[8] = {0xFE,0xFD,0xFB,0xF7,0xEF,0xDF,0xBF,0x7F}; // 逐个点亮的数码管数据
unsigned char count1 = 0, count2 = 0; // 计数器
unsigned char flag1 = 0, flag2 = 0; // 标志位
unsigned char mode = 0; // 模式
void init() {
TMOD = 0x10; // 定时器2工作在模式1
TH1 = 0xFC; // 定时器2初值
TL1 = 0x66;
ET1 = 1; // 允许定时器2中断
TR1 = 1; // 启动定时器2
EX0 = 1; // 允许外部中断0
IT0 = 1; // 设置为下降沿触发
EX1 = 1; // 允许外部中断1
IT1 = 1; // 设置为下降沿触发
EA = 1; // 允许中断
}
void main() {
init();
while (1) {
switch (mode) {
case 0: // 跑马灯模式
LED3 = 0;
LED4 = 0;
delay(300);
LED3 = 1;
LED4 = 1;
LED2 = 0;
LED5 = 0;
delay(300);
LED2 = 1;
LED5 = 1;
LED1 = 0;
LED6 = 0;
delay(300);
LED1 = 1;
LED6 = 1;
LED2 = 0;
LED5 = 0;
delay(300);
LED2 = 1;
LED5 = 1;
LED3 = 0;
LED4 = 0;
delay(300);
LED3 = 1;
LED4 = 1;
break;
case 1: // 按键模式1
if (flag1 == 0 && KEY1 == 0) {
flag1 = 1;
}
if (flag1 == 1 && KEY1 == 1) {
count1++;
if (count1 >= 3) {
count1 = 0;
flag1 = 0;
}
}
switch (count1) {
case 0:
LED0 = LED1 = 0;
LED2 = LED3 = 1;
LED4 = LED5 = 1;
LED6 = LED7 = 1;
delay(200);
break;
case 1:
LED0 = LED1 = 1;
LED2 = LED3 = 0;
LED4 = LED5 = 1;
LED6 = LED7 = 1;
delay(200);
break;
case 2:
LED0 = LED1 = 1;
LED2 = LED3 = 1;
LED4 = LED5 = 0;
LED6 = LED7 = 1;
delay(200);
break;
}
break;
case 2: // 按键模式2
if (flag2 == 0 && KEY3 == 0) {
flag2 = 1;
}
if (flag2 == 1 && KEY3 == 1) {
count2++;
if (count2 >= 5) {
count2 = 0;
flag2 = 0;
}
}
if (count2 % 2 == 0) {
LED0 = LED7 = 0;
LED1 = LED6 = 1;
LED2 = LED5 = 1;
LED3 = LED4 = 1;
} else {
LED0 = LED7 = 1;
LED1 = LED6 = 1;
LED2 = LED5 = 1;
LED3 = LED4 = 1;
}
delay(400);
break;
}
}
}
void Timer1() interrupt 3 { // 定时器2中断服务函数
TH1 = 0xFC; // 重新设置定时器2初值
TL1 = 0x66;
if (mode == 0) {
static unsigned char i = 0;
switch (i) {
case 0:
P1 = LED[0];
break;
case 1:
P1 = LED[1];
break;
case 2:
P1 = LED[2];
break;
case 3:
P1 = LED[1];
break;
case 4:
P1 = LED[0];
break;
}
i = (i + 1) % 5;
}
}
void External0() interrupt 0 { // 外部中断0服务函数
mode = 1; // 切换到按键模式1
}
void External1() interrupt 2 { // 外部中断1服务函数
mode = 2; // 切换到按键模式2
}
void delay(unsigned int t) { // 延时函数
unsigned int i, j;
for (i = 0; i < t; i++) {
for (j = 0; j < 1000; j++) {
// 空循环
}
}
}
```
以上是使用寄存器编写的代码实现,具体的操作流程和函数实现需要根据实际情况进行调整。
阅读全文