要求:用51单片机设计一个波形发生器,可以产生方波、三角波、正弦波、锯齿波,波形幅度可调、频率可调。
仿真电路组成:
初始化参数
#include<reg51.h> //51头文件
#define uchar unsigned char
#define uint unsigned int
sbit s1=P3^2;
sbit s2=P3^3;
uchar k=0,p=0,delay=0;
uchar bxxz=0;pinglv=0;
uchar a=1,b=0,c=0,d=0;
//正弦波数据
uchar code sin[64]={
135,145,158,167,176,188,199,209,218,226,234,240,245,249,252,254,254,253,251,247,243,237,230,222,213,204,193,182,170,158,
146,133,121,108,96,84,72,61,50,41,32,24,17,11,7,3,1,0,0,2,5,9,14,20,28,36,45,55,66,78,90,102,114,128
};
//方波数据报表
uchar code juxing[64]={
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
};
//锯齿波数据
uchar code juchi[64]={
0,4,8,12,16,20,24,28,32,36,40,45,49,53,57,61,65,69,73,77,81,85,89,93,97,101,105,109,113,117,121,125,130,134,138,142,
146,150,154,158,162,166,170,174,178,182,186,190,194,198,202,206,210,215,219,223,227,231,235,239,243,247,251,255
};
//三角波数据
uchar code sanjiao[64]={
0,8,16,24,32,40,48,56,64,72,80,88,96,104,112,120,128,136,144,152,160,168,176,184,192,200,208,216,224,232,240,248,
248,240,232,224,216,208,200,192,184,176,168,160,152,144,136,128,120,112,104,96,88,80,72,64,56,48,40,32,24,16,8,0
};
延时子程序
void delay1() //延时 ms级
{
int a,b;
for(a=1;a>0;a--)
for(b=122;b>0;b--);
}
外部中断0子程序
void int0() interrupt 0 //外部中断0 P3.2 中断处理,用于波形切换
{
EX0=0;
delay1();
if(s1==0)
{
bxxz++;
if(bxxz==4)
bxxz=0;
switch(bxxz)
{
case 0 :
{a=1,b=0,c=0,d=0;} //正弦波
break;
case 1 :
{a=0,b=1,c=0,d=0;} //方波
break;
case 2 :
{a=0,b=0,c=1,d=0;} //锯齿波
break;
case 3 :
{a=0,b=0,c=0,d=1;} //三角波
break;
}
delay1();
while(!s1);
}
while(!s1);
EX0=1;
}
外部中断1子程序
void int1() interrupt 2 //外部中断1 P3.3 中断处理,用于频率调节
{
EX1=0;
delay1();
if(s2==0){
p++;
if(p==8)
p=0;
switch(p)
{
case 1 :
pinglv=4; //400Hz
break;
case 2 :
pinglv=8; //250Hz
break;
case 3 :
pinglv=16; //140Hz
break;
case 4 :
pinglv=32; //75Hz
break;
case 5 :
pinglv=64; //40Hz
break;
case 6 :
pinglv=125; //20Hz
break;
case 7 :
pinglv=255; //10Hz
break;
default :
pinglv=0; //1000Hz
break;
}
delay1();
while(!s2);
}
while(!s2);
EX1=1; //开中断
}
主函数
void main()
{
EA=1;
IT0=1;
EX0=1;
IT1=1;
EX1=1;
pinglv=15;
while(1)
{
while(a) //产生正弦波
{
delay=pinglv; //获取周期数据
P2=sin[k]; //数据数P2口进行波形转换
k++;
if(k==64) //一个周期取64点波数据
k=0;
while(delay) //延时处理
delay--;
}
while(b) //产生方波
{
delay=pinglv;
P2=juxing[k];
k++;
if(k==64)
k=0;
while(delay)
delay--;
}
while(c) //产生锯齿波
{
delay=pinglv;
P2=juchi[k];
k++;
if(k==64)
k=0;
while(delay)
delay--;
}
while(d) //产生三角波
{
delay=pinglv;
P2=sanjiao[k];
k++;
if(k==64)
k=0;
while(delay)
delay--;
}
}
}
正弦波
方波
锯齿波
三角波
频率可调
幅度可调
简单实现波形发生器,设计达到要求。
作者:叶庭云 CSDN:https://yetingyun.blog.csdn.net/