生成c51语言代码:1、音乐盒上电数码管显示器自动显示P.。该音乐盒可以通过P1口的键盘选择曲目、切换曲目。该音乐盒可以通过P2口的数码管显示曲目编号2、按键能发出do,re,mi...
时间: 2024-03-18 19:38:46 浏览: 17
以下是使用 C51 语言编写的代码:
```
#include <reg51.h>
// 定义数码管显示表
unsigned char code DisplayTable[] = {
0xC0, 0xF9, 0xA4, 0xB0, 0x99, 0x92, 0x82, 0xF8, 0x80, 0x90
};
// 定义按键值
unsigned char code KeyTable[] = {
0x7F, 0xBF, 0xDF, 0xEF, 0xF7, 0xFB, 0xFD, 0xFE
};
// 定义曲目编号
unsigned char code SongTable[] = {
0x01, 0x02, 0x03, 0x04, 0x05
};
// 定义初始曲目编号
unsigned char SongIndex = 0x01;
// 定义函数延时
void Delay(unsigned int n)
{
unsigned int i, j;
for (i = 0; i < n; i++)
for (j = 0; j < 125; j++);
}
// 定义数码管显示函数
void Display(unsigned char n)
{
P2 = DisplayTable[n];
}
// 定义按键扫描函数
unsigned char KeyScan()
{
unsigned char i, j, k, KeyValue;
for (i = 0; i < 8; i++)
{
P1 = KeyTable[i];
if (P1 != KeyTable[i])
continue;
for (j = 0; j < 8; j++)
{
k = 1 << j;
if ((P1 & k) == 0)
{
KeyValue = i * 8 + j;
while ((P1 & k) == 0);
return KeyValue;
}
}
}
return 0xFF;
}
// 主函数
void main()
{
unsigned char KeyValue;
while (1)
{
// 数码管显示曲目编号
Display(SongIndex);
// 按键扫描
KeyValue = KeyScan();
if (KeyValue != 0xFF)
{
// 按键发出声音
switch (KeyValue)
{
case 0x00: // do
// 发出do声音
break;
case 0x01: // re
// 发出re声音
break;
case 0x02: // mi
// 发出mi声音
break;
// 其他按键...
}
}
// 判断是否需要切换曲目
if (KeyValue == 0x00) // P1.7
{
Delay(10); // 延时去抖动
if (P1 == 0x7F) // P1.0~P1.6都是高电平
{
SongIndex++;
if (SongIndex > sizeof(SongTable))
SongIndex = 0x01;
}
}
}
}
```
该代码实现了音乐盒上电数码管显示器自动显示 P,通过 P1 口的键盘选择曲目、切换曲目,通过 P2 口的数码管显示曲目编号,按键能发出 do、re、mi 等声音。其中,键值通过按键扫描函数 KeyScan() 获取,曲目编号和按键值通过代码中的数组定义,发出声音的部分需要根据实际情况进行补充。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)