基于51单片机的简易电子琴设计
转载地址: https://blog.csdn.net/zy010101/article/details/80538312
基于51单片机设计的简易电子琴下面直接给出proteus仿真
电路代码如下:
#include <reg51.h>
#define uint unsigned int
#define uchar unsigned char
#define output P1
#define input P1
//方便移植在其他电路板上,我的电路使用P1口做键盘输入接口
//定义16个按键
enum KEY{key0,key1,key2,key3,key4,key5,key6,key7,key8,key9,key10,key11,key12,key13,key14,key15};
uchar code table[]={ //数组定义,显示数码管
0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,
0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71,0x00};
unsigned int code Freqtab[] = { //定时半周期的初始值
64021,64103,64260,64400, //低音3 4 5 6
64524,64580,64684,64777, //低音7,中音1 2 3
64820,64898,64968,65030, //中音4 5 6 7
65058,65110,65157,65178}; //高音1 2 3 4
uint FreqTemp;
//蜂鸣器声音不怎么样,我们使用扬声器,接P3.7口
sbit SPEAK = P3^7;
void delay1ms(uint n) //误差 0us ,延时n毫秒
{
uint a,b,c;
for(c=n;c>0;c--)
for(b=199;b>0;b--)
for(a=1;a>0;a--);
}
uint key_input(void)
{
uchar temp1,temp2; //临时保存读取的行或者列
uchar num = 16; //返回按键的值
output = 0x0f;
temp1 = input; //先读取行
if(0x0f != temp1) //按键按下
{
delay1ms(5); //延时,消除抖动
temp1 = input; //再次读取行
if(0x0f != temp1) //说明按键确实按下
{
temp1 = temp1 & 0x0f; //保留低4位
output = 0xf0; //准备读取列
delay1ms(1); //延时一下,防止下一句读不到
temp2 = input; //直接读取列
temp2 = temp2 & 0xf0; //保留高4位
temp1 = temp1 | temp2; //将temp1和temp2的值合并
}
}
switch(temp1)
{
case 0xee:num=0;break;
case 0xde:num=1;break;
case 0xbe:num=2;break;
case 0x7e:num=3;break;
case 0xed:num=4;break;
case 0xdd:num=5;break;
case 0xbd:num=6;break;
case 0x7d:num=7;break;
case 0xeb:num=8;break;
case 0xdb:num=9;break;
case 0xbb:num=10;break;
case 0x7b:num=11;break;
case 0xe7:num=12;break;
case 0xd7:num=13;break;
case 0xb7:num=14;break;
case 0x77:num=15;break;
default:break;
}
return num;
}
void T0_INT(void) interrupt 1
{
TL0 = FreqTemp; //载入定时半周期的初始值
TH0 = FreqTemp >> 8;
SPEAK = ~SPEAK; //发音
}
int main()
{
TMOD = 0X01; //定时器T0设置为方式1
EA = 1;
ET0 = 1;
TR0 = 0;
while(1)
{
uint num,temp;
num = key_input();
temp = num;
P0 = table[num];
if(16 != num)
{
FreqTemp = Freqtab[num];
TR0 = 1;
while(0xf0 != output); //检测按键松开
TR0 = 0;
SPEAK = 1;
}
}
return 0;
}
扫描加入电子开发圈,海量云盘学习资料等你下载!