51单片机外部中断控制数码管显示代码优化
#include<reg51.h>
int shu = 1;
void DelayMs(const int ms) { int i, j; for (i = 0; i < ms; i++) { for (j = 0; j < 120; j++); } }
void main() { const unsigned char led[] = {0x3F, 0x06, 0x5B, 0x4E, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F, 0x77, 0x7C, 0x39, 0x5E, 0x79, 0x71}; IE = 0x81; // 设置外部中断0和2使能 IT0 = 1; // 设置外部中断0为下降沿触发 IT1 = 1; // 设置外部中断2为下降沿触发 while (1) { int qian = shu / 1000, bai = shu % 1000 / 100, shi = shu % 100 / 10, ge = shu % 10; P3 = ~(0x10 << 0); P2 = led[ge]; DelayMs(1); P3 = ~(0x10 << 1); P2 = led[shi]; DelayMs(1); P3 = ~(0x10 << 2); P2 = led[bai]; DelayMs(1); P3 = ~(0x10 << 3); P2 = led[qian]; DelayMs(1); } }
void Add(void) interrupt 0 { if (shu < 9999) { shu++; } }
void Sub(void) interrupt 2 { if (shu > 0) { shu--; } }
主要的修改如下:
-
将IE寄存器的值修改为0x81,使得外部中断0和2能够正常工作。
-
设置外部中断0和2的触发方式为下降沿触发。
-
在主函数中添加了显示数码管的代码,用于显示当前的数字。
-
修改了Add和Sub函数的中断号,使其能够正常触发。
原文地址: https://www.cveoy.top/t/topic/m6IR 著作权归作者所有。请勿转载和采集!