51单片机电子记分牌编程代码:实现加减分和复位功能
#include <reg51.h>
// 定义数码管显示的数字编码 unsigned char code num_code[] = { 0x3f, // 0 0x06, // 1 0x5b, // 2 0x4f, // 3 0x66, // 4 0x6d, // 5 0x7d, // 6 0x07, // 7 0x7f, // 8 0x6f // 9 };
// 初始化全局变量 unsigned char score = 50; // 初始分数为50
// 函数声明 void delay(unsigned int ms); void display_score(unsigned char score); void beep(unsigned int ms);
// 主函数 void main() { // 设置P0口为输出口 P0 = 0xff; P1 = 0xff;
// 设置P2口为输入口,K1、K2、K3连接的是P2口的0、1和2引脚
P2 = 0xff;
// 选择12MHz晶振
TMOD = 0x01;
// 主循环
while (1) {
// 判断K1按钮是否按下
if (P2_0 == 0) {
delay(10); // 延时去抖动
if (P2_0 == 0) {
score++; // 加1分
display_score(score); // 显示分数
beep(100); // 发出提示音
}
}
// 判断K2按钮是否按下
if (P2_1 == 0) {
delay(10); // 延时去抖动
if (P2_1 == 0) {
score--; // 减1分
display_score(score); // 显示分数
beep(100); // 发出提示音
}
}
// 判断K3按钮是否按下
if (P2_2 == 0) {
delay(10); // 延时去抖动
if (P2_2 == 0) {
score = 50; // 复位分数为50
display_score(score); // 显示分数
beep(100); // 发出提示音
}
}
}
}
// 延时函数 void delay(unsigned int ms) { unsigned int i, j; for (i = 0; i < ms; i++) for (j = 0; j < 110; j++); }
// 显示分数函数 void display_score(unsigned char score) { unsigned char tens, units; tens = score / 10; // 十位数 units = score % 10; // 个位数
// 显示十位数
P1 = num_code[tens];
P0 = 0xfe;
delay(1);
P0 = 0xff;
// 显示个位数
P1 = num_code[units];
P0 = 0xfd;
delay(1);
P0 = 0xff;
}
// 蜂鸣器发声函数 void beep(unsigned int ms) { TH0 = (65536 - 50000) / 256; TL0 = (65536 - 50000) % 256; TR0 = 1; // 启动定时器0
// 延时一段时间
delay(ms);
TR0 = 0; // 停止定时器0
}
原文地址: https://www.cveoy.top/t/topic/pAUp 著作权归作者所有。请勿转载和采集!