程序是为了测试AD转换功能,只用到P1^0一路作为AD转换,大于设定数值对应LED亮,但目前程序完全不受外部电压控制,接上0V或者5V甚至不接悬空,其结果也是一样的,无任何变化,请高手帮忙分析分析问题出在哪里。外围电路是根据STC手册上接的(电压信号源通过一个1K的电阻之后并一个47PF的电容连接到P1^0口)。
#include<reg51.h>
#include "intrins.h"
#define uchar unsigned char
#define uint unsigned int
uchar Vo; //A/D转换后换算的电压值
/*Declare SFR associated with the ADC */
sfr ADC_CONTR = 0xBC; //ADC control register
sfr ADC_RES = 0xBD; //ADC high 8-bit result register
sfr ADC_RESL = 0xBE;
//sfr ADC_LOW2 = 0xBE; //ADC low 2-bit result register
sfr P1ASF = 0x9D; //P1 secondary function control register
/*Define ADC operation const for ADC_CONTR*/
#define ADC_POWER 0x80 //ADC power control bit
#define ADC_FLAG 0x10 //ADC complete flag 模数转换结束标志位
#define ADC_START 0x08 //ADC start control bit 模数转换启动控制位
//转换速度控制位SPEED0和SPEED1,共四种状态,对应四种转换速度
#define ADC_SPEEDLL 0x00 //540 clocks
#define ADC_SPEEDL 0x20 //360 clocks
#define ADC_SPEEDH 0x40 //180 clocks
#define ADC_SPEEDHH 0x60 //90 clocks
sbit LED7 = P1^7;
sbit LED5 = P1^5;
void DelayMS(uint ms)
{
uint i;
while(ms--)
{
for(i=0;i<120;i++);
}
}
/*----------------------------
Software delay function
----------------------------*/
void Delay(uint n)
{
uint x;
while (n--)
{
x = 5000;
while (x--);
}
}
/*----------------------------
Initial ADC sfr
----------------------------*/
void InitADC()
{
P1ASF = 0x01; //选择P1.0作为A/D输入通道
ADC_RES = 0; //清0
ADC_CONTR = ADC_POWER | ADC_SPEEDLL; //0x10|0x00=0x10:开电源和设置A/D转换速度
Delay(2); //ADC power-on and delay
}
/*----------------------------
Get ADC result
----------------------------*/
uchar GetADCResult(uchar ch)
{
ADC_CONTR = ADC_POWER | ADC_SPEEDLL | ch | ADC_START;//0x00|0x00|ch|0x08:选择A/D输入通道,开始A/D转换
_nop_(); //Must wait before inquiry ,
_nop_(); //设置ADC_CONTR寄存器后需加4个CPU时钟周期的延时,才能保证值被写入ADC_CONTR寄存器
_nop_();
_nop_();
while (!(ADC_CONTR & ADC_FLAG));//Wait complete flag
ADC_CONTR &= ~ADC_FLAG; //Close ADC
Vo=ADC_RES*5*10/256; //Return ADC result(为显示整数,这里将电压值扩大了十倍)
return Vo;
}
void main()
{
InitADC();
while (1)
{
GetADCResult(0);
if (GetADCResult(0) >= 40)
{
LED7 = 0; LED5 = 1;
}
else
{
LED5 = 0; LED7 = 1;
}
DelayMS(1000);
}
}
|