基于STC12C56系列單片機(jī)的AD轉(zhuǎn)換C程序
/****************
STC12c56 AD轉(zhuǎn)換
入口參數(shù):通道數(shù)(0,1,2,3,4,5,6,7)
返回值: AD轉(zhuǎn)換結(jié)果
*****************/
#includereg51.h>
sfr ADC_CONTR=0xc5; //AD轉(zhuǎn)換寄存器
sfr ADC_DATA=0xc6; //AD轉(zhuǎn)換結(jié)果寄存器,為10位
sfr P1M0=0x91;
sfr P1M1=0x92;
/***************************
微秒延時函數(shù)
********************************/
void delay_us(unsigned int i)//延時 如果需要高精度延時 請嵌入?yún)R編
{
unsigned char a;
if (i == 0)
{
return ;
}
for (a = 1; a i; a++)
{
;
}
}
/***************************
毫秒延時函數(shù)
********************************/
void delay_ms(int num)
{
int x,y;
for(y=0;ynum;y++)
{
for(x = 0;x 5000;x)
x++;
}
}
/*********************
入口參數(shù):通道數(shù)(0,1,2,3,4,5,6,7)
返回值: AD轉(zhuǎn)換結(jié)果
**************************/
unsigned char AD(unsigned char Channel)
{
unsigned char ADResult;
ADC_CONTR|=0x80; //開AD轉(zhuǎn)換電源
delay_ms(1); //延時1ms
switch(Channel)
{
case 0:
P1M0|=0x01;P1M1|=0x01; //設(shè)置開漏
ADC_CONTR=0xe0; //選擇AD轉(zhuǎn)換通道
break;
case 1:
P1M0|=0x02;P1M1|=0x02;
ADC_CONTR=0xe1;
break;
case 2:
P1M0|=0x04;P1M1|=0x04;
ADC_CONTR=0xe2;
break;
case 3:
P1M0|=0x08;P1M1|=0x08;
ADC_CONTR=0xe3;
break;
case 4:
P1M0|=0x10;P1M1|=0x10;
ADC_CONTR=0xe4;
break;
case 5:
P1M0|=0x20;P1M1|=0x20;
ADC_CONTR=0xe5;
break;
case 6:
P1M0|=0x40;P1M1|=0x40;
ADC_CONTR=0xe6;
break;
case 7:
P1M0|=0x80;P1M1|=0x80;
ADC_CONTR=0xe7;
break;
}
delay_us(100);
ADC_DATA=0x00;
ADC_CONTR|=0x08; //啟動AD轉(zhuǎn)換
delay_us(200); //等待轉(zhuǎn)換完成
ADC_CONTR=0xe7; //清0 ADC_FLAG,ADC_START 位,停止AD轉(zhuǎn)換
ADResult=ADC_DATA; //保存轉(zhuǎn)換結(jié)果
switch(Channel)
{
case 0:
P1M0=0xfe;P1M1=0xfe; //設(shè)置普通IO
break;
case 1:
P1M0=0xfd;P1M1=0xfd;
break;
case 2:
P1M0=0xfb;P1M1=0xfb;
break;
case 3:
P1M0=0xf7;P1M1=0xf7;
break;
case 4:
P1M0=0xef;P1M1=0xef;
break;
case 5:
P1M0=0xdf;P1M1=0xdf;
break;
case 6:
P1M0=0xbf;P1M1=0xbf;
break;
case 7:
P1M0=0x7f;P1M1=0x7f;
break;
}
return ADResult;
}
評論