原程序过于复杂 修改后舍去了外部中断优化了程序结构 用数组替换了原来的正弦波产生函数 添加了部分注释
程序和仿真比较完美了
能产生比较完美的正弦波了,也比较容易理解。
仿真原理图如下(proteus仿真工程文件可到本帖附件中下载)
单片机源程序如下:
- /*******************************************************************
- 感谢javaleilei的分享
- 对于之前程序过于复杂 舍去了外部中断优化了程序结构 用数组替换了原来的正弦波产生函数 添加了部分注释
- 程序和仿真比较完美了
- 最终修改 BY:Pia Ji
- *******************************************************************/
- #include <reg51.h>
- unsigned char flag=0;
- sbit key1 = P3^0;
- sbit key2 = P3^1;
- sbit key3 = P3^2;
- sbit key4 = P3^3;
- unsigned char code sin_num[]={
- 0,0,0,0,0,0,0,0,1,1,1,1,1,2,2,2,
- 2,3,3,4,4,4,5,5,6,6,7,7,8,8,9,9,
- 10,10,11,12,12,13,14,15,15,16,17,18,18,19,20,21,
- 22,23,24,25,25,26,27,28,29,30,31,32,34,35,36,37,
- 38,39,40,41,42,44,45,46,47,49,50,51,52,54,55,56,
- 57,59,60,61,63,64,66,67,68,70,71,73,74,75,77,78,
- 80,81,83,84,86,87,89,90,92,93,95,96,98,99,101,102,
- 104,106,107,109,110,112, 113,115,116,118,120,121,123,124,126,128,
- 129,131, 132,134,135, 137, 139,140,142,143,145,146,148, 149,151,153,
- 154,156,157,159,160,162,163,165, 166,168,169,171,172,174,175,177,
- 178,180,181, 182,184,185,187,188,189,191,192,194,195,196,198,199,
- 200,201,203,204,205,206,208,209,210,211,213,214,215,216,217,218,
- 219,220,221,223,224,225,226,227,228,229,230,230,231,232,233,234,
- 235,236,237,237,238,239,240,240,241,242,243,243,244,245,245,246,
- 246,247,247,248,248,249,249,250,250,251,251, 251,252,252,253,253,
- 253,253,254,254,254,254,254,255,255,255,255, 255,255,255,255,255
- }; //这是正弦波上升半周期的采样
- void delay(unsigned int x)//延时
- {
- while(--x);
- }
- void key_pors()//按键处理函数
- {
- if(key1==0)
- flag=0;
- else if(key2==0)
- flag=1;
- else if(key3==0)
- flag=2;
- else if(key4==0)
- flag=3;
- }
- void show_wave()
- {
- int i;
- switch(flag)
- {
- case 0: //三角波
- for(i=0;i<255;i++)
- {
- P1=i;
- }
- for(i=255;i>0;i--)
- {
- P1=i;
- }
- break;
-
- case 1://方波
- P1=0;
- delay(100);
- P1=0xff;
- delay(100);
- break;
-
- case 2://三角波
- for(i=255;i>0;i--)
- P1=i;
- break;
-
- case 3: //正弦波 采用数组采样值 波形更好
- for(i=0;i<255;i++)
- P1=sin_num[i];
- for(i=255;i>=0;i--)
- P1=sin_num[i];
- break;
- default : P1=0;//否则为0 防错
- }
- }
- void main()
- {
- while(1)
- {
- key_pors();
- show_wave();
- }
- }
复制代码
所有资料51hei提供下载:
四种波形发生器.zip
(102.28 KB, 下载次数: 185)
|