代码解释#include <reg51.h> #define uchar unsigned char #define uint unsigned int // c0de for 7Seg MPX CA, from 0 to 9 and A to F and - // if want to use in CC, add ~ uchar code numberDisplayTable[] = {0xc0, 0xf9, 0xa4, 0xb0, 0x99, 0x92, 0x82, 0xf8, 0x80, 0x90, 0x88, 0x83, 0xc6, 0xa1, 0x86, 0x8e, 0xbf}; // delay time for notes uint code noteDelayTime[] = {64021, 64103, 64260, 64400, 64524, 64580, 64684, 64777, 64820, 64898, 64968, 65030, 65058, 65110, 65157, 65178}; sbit BEEP = P3 ^ 0; uchar keyNumber; void delay(uchar x) { uchar i; while (x--) for(i = 0; i < 120; i++); } void scanKey() { uchar tmp, k; P1 = 0x0f; delay(2); tmp = P1 ^ 0x0f; switch (tmp) { case 1: k = 0; break; case 2: k = 1; break; case 4: k = 2; break; case 8: k = 3; break; default:// no key down? return; } // set low 4 bits to 0, so place in 4 rows P1 = 0xf0; delay(2); // after button push, 11110000 will turned into XXXX0000, 1 0 in X, 3 1 in X // so we extract the 0 out tmp = (P1 >> 4) ^ 0x0f; // set 0,4,8,12 for row 0 ~ 3 switch (tmp) { case 1: k += 0; break; case 2: k += 4; break; case 4: k += 8; break; case 8: k += 12; break; default: return; } keyNumber = k; } // play sound via int0 void playNote() interrupt 1 { TH0 = noteDelayTime[keyNumber] / 256; TL0 = noteDelayTime[keyNumber] % 256; BEEP = ~BEEP; } void main() { // display - at start P0 = 0xbf; TMOD = 0x01; IE = 0x82; while (1) { // send scanner P1 = 0xf0; // if button down if (P1 != 0xf0) { scanKey(); P0 = ~numberDisplayTable[keyNumber]; // enable timer TR0 = 1; } else { // stop timer TR0 = 0; } delay(2); } }
时间: 2024-05-02 07:22:04 浏览: 102
#indef 与#define 区别于用法
这是一段8051单片机的程序代码,主要实现了一个数字键盘的输入和对应的数字音符的播放功能。具体来说,代码中使用了一个数字表来表示0~9和A~F以及“-”这些数字在数码管上的显示方式(使用了共阴极的7段数码管),同时也定义了一个数组来表示每个音符需要延时的时间。在主函数中,程序通过扫描数字键盘的输入来获取用户按下的键号,并根据键号找到对应的音符延时时间,然后通过定时器来实现音符的播放。同时,程序也根据键号将对应的数字在数码管上进行显示。整个程序的逻辑比较清晰,主要是通过数字表和延时时间表来实现功能。
阅读全文