程序如下,启动AD转换,结果通过串口送出,第一次转换结果是正确的,以后的数据全是错误的。 // ad test #include <reg52.h>
/*A/D SFR*/ //sfr ADC_LOW2 = 0xBE; sfr ADC_CONTR = 0xC5; sfr ADC_DATA = 0xC6; //sfr CLK_DIV = 0xC7; sfr P1M0 = 0x91; sfr P1M1 = 0x92;
sbit led=P1^7; sbit led2=P1^6; unsigned char rec;
void delay(unsigned int i) { while(i--); return; } void ad_init(void) { ADC_CONTR = ADC_CONTR|0x80; //启动AD转换电源 delay(3000); //延时大于1ms,使电源稳定 P1M0 = P1M0|0x04; //00000100,设置P1.2为开漏 P1M1 = P1M1|0x04; ADC_CONTR = ADC_CONTR|0xE2; //11100010,设置P1.2为AD输入通道 delay(600); //切换AD通道后,延时200us,如果输入信号电压的内阻小于10K,可不用延时 } void set_nor(void) { P1M0 = P1M0|0xfb; //11111011,设置P1.2为NORMAL模式 P1M1 = P1M1|0xfb; } void start_ad(void) { ADC_DATA = 0; ADC_CONTR = ADC_CONTR|0x08; //00001000,启动AD转换 } void stop_ad(void) { ADC_CONTR = ADC_CONTR|0xef; //11100111,停止AD转换,并清除AD FLAG } bit is_ad_ok(void) { unsigned char tt; tt = ADC_CONTR; if(tt&0x10==1) return(1); else return(0); } void sendbyte(unsigned char dat) { SBUF = dat; while(TI==0); TI = 0; } void uart(void) interrupt 4 { if(RI) { RI = 0; rec = SBUF; } if(TI) { TI = 0; } } void uartinit(void) { TMOD = 0x21; TL1 = 0xFa; TH1 = 0xFa; SCON = 0x50; PCON = 0x00; TR1 = 1; ES = 1; //EA = 1; } void ad(void) { ad_init(); start_ad(); delay(50000); sendbyte(ADC_DATA); stop_ad(); set_nor(); }
void main(void) { unsigned char i; uartinit(); sendbyte(0x12); ad_init(); start_ad(); delay(50000); sendbyte(ADC_DATA); stop_ad(); set_nor(); while(1) { led = 0; if(rec==0x11) { //sendbyte(i++); led2 = !led2; rec = 0; } ad(); delay(50000); led = 1; delay(50000); } }
|