本帖最后由 tsslisimin 于 2013-7-24 09:58 编辑
#include "stc12.h"
#define uint unsigned int
#define uchar unsigned char
sbit key1=P4^0;
sbit key2=P4^1;
sbit Din=P1^5;
sbit adcs=P3^5;
sbit clk=P1^7;
uchar flag=0,key_count=0,i=0;
uchar frequency=1;//默认输出频率为1HZ
void keyscan();
void delay(uchar z);
unsigned char code sin_tab[] = //正弦波输出表
{
//从0到最大值
0x80,0x83,0x86,0x89,0x8D,0x90,0x93,0x96,0x99,0x9C,0x9F,0xA2,0xA5,0xA8,0xAB,0xAE,
0xB1,0xB4,0xB7,0xBA,0xBC,0xBF,0xC2,0xC5,0xC7,0xCA,0xCC,0xCF,0xD1,0xD4,0xD6,0xD8,
0xDA,0xDD,0xDF,0xE1,0xE3,0xE5,0xE7,0xE9,0xEA,0xEC,0xEE,0xEF,0xF1,0xF2,0xF4,0xF5,
0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFD,0xFE,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
//从最大值到0
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE,0xFD,0xFD,0xFC,0xFB,0xFA,0xF9,0xF8,0xF7,0xF6,
0xF5,0xF4,0xF2,0xF1,0xEF,0xEE,0xEC,0xEA,0xE9,0xE7,0xE5,0xE3,0xE1,0xDF,0xDD,0xDA,
0xD8,0xD6,0xD4,0xD1,0xCF,0xCC,0xCA,0xC7,0xC5,0xC2,0xBF,0xBC,0xBA,0xB7,0xB4,0xB1,
0xAE,0xAB,0xA8,0xA5,0xA2,0x9F,0x9C,0x99,0x96,0x93,0x90,0x8D,0x89,0x86,0x83,0x80,
//从0到最少值
0x80,0x7C,0x79,0x76,0x72,0x6F,0x6C,0x69,0x66,0x63,0x60,0x5D,0x5A,0x57,0x55,0x51,
0x4E,0x4C,0x48,0x45,0x43,0x40,0x3D,0x3A,0x38,0x35,0x33,0x30,0x2E,0x2B,0x29,0x27,
0x25,0x22,0x20,0x1E,0x1C,0x1A,0x18,0x16,0x15,0x13,0x11,0x10,0x0E,0x0D,0x0B,0x0A,
0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x02,0x01,0x00,0x00,0x00,0x00,0x00,0x00,
//从最小值到0
0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x02,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,
0x0A,0x0B,0x0D,0x0E,0x10,0x11,0x13,0x15,0x16,0x18,0x1A,0x1C,0x1E,0x20,0x22,0x25,
0x27,0x29,0x2B,0x2E,0x30,0x33,0x35,0x38,0x3A,0x3D,0x40,0x43,0x45,0x48,0x4C,0x4E,
0x51,0x55,0x57,0x5A,0x5D,0x60,0x63,0x66,0x69,0x6C,0x6F,0x72,0x76,0x79,0x7C,0x7E
};
void Sintranslator(uint wdata)//正弦波
{
unsigned char j;
adcs=0;//片选使能
wdata<<=2;//将数据左移两位,补两位扩展位,组成12位数据写入
for(j=0;j<12;j++)//写入12位数据
{
clk=0;
Din=(wdata&0x0800)?1:0;//取出最高位(第11位)写入
clk=1;//上升沿送数据
wdata<<=1;//下一位移到最高位
}
adcs=1;//片选禁止
}
void main()
{
TMOD=0x01; //确定定时器的工作方式
/*初始频率为1hZ 一百万除256为3906 近似4MS进一次中断
即4MS打一个点 有256个点 4*256=1024ms 近似1ms 所以频率为1HZ
后面的以此类推 */
TH0=(65536-1000000/(frequency*256))/256;//给定时器0赋予初值
TL0=(65536-1000000/(frequency*256))%256;
EA=1; //开总中断
ET0=1; //开启定时器0中断
TR0=1; //计数开始
while(1)
{
keyscan();
if(key_count==1)
{
while(i<256)
{
while(!flag);//等中断
TR0=0;//为了使定时器精确点,所以就在这里使定时器停止计数
Sintranslator(4*sin_tab);//只打一个点
i++;
flag=0;
if(i==256)i=0;
TR0=1;//开始计数
break;//跳出循环
}
}
}
}
void delay(uchar z) //延时函数
{
uchar x,y;
for(x=0;x<110;x++)
for(y=z;y>0;y--);
}
void keyscan() //切换功能按键返回键值函数
{
if(key1==0)
{
TR0=0;//停止计数
delay(10);//按键消抖
if(key1==0)
{
key_count++;//使出现正弦波
if(key_count==2)
key_count=0;
while(!key1);//松手检测
}
}
if(key2==0)
{
TR0=0;
delay(10);
if(key2==0)
{
frequency=frequency+1;//通过按key2改变定时器的初值,即改变频率,这里使频率每次加1
if(frequency==100)frequency=0;
while(!key2); //松手检测
}
}
TR0=1;//开始计数
}
void Time0() interrupt 1
{
TR0=0;//停止计数
TH0=(65536-1000000/(frequency*256))/256;
TL0=(65536-1000000/(frequency*256))%256;
flag=1;//打点的标志符
TR0=1;//开始计数
}
|