AD转换获取土壤的湿度
#include "reg52.h"
#include "intrins.h"
#define MYID 0x05
#define UPID 0x01
sfr AUXR = 0x8e;
sfr ADC_CONTR = 0xBC;
sfr ADC_RES = 0xBD;
sfr ADC_LOW2 = 0xBE;
sfr P1ASF = 0x9D;
#define ADC_POWER 0x80
#define ADC_FLAG 0x10
#define ADC_START 0x08
#define ADC_SPEEDLL 0x00
#define ADC_SPEEDL 0x20
#define ADC_SPEEDH 0x40
#define ADC_SPEEDHH 0x60
unsigned char bufsend[10] = { 0 };
void Delay1ms(unsigned int x)
{
unsigned char i, j;
while( x -- ){
_nop_();
_nop_();
_nop_();
i = 11;
j = 190;
do
{
while (--j);
} while (--i);
}
}
void UartInit()
{
PCON |= 0x80;
SCON = 0x50;
AUXR &= 0xBF;
AUXR &= 0xFE;
TMOD &= 0x0F;
TMOD |= 0x20;
TL1 = 0XFA;
TH1 = 0xFA;
ET1 = 0;
TR1 = 1;
}
void InitADC(){
P1ASF = 0x01;
ADC_RES = 0;
ADC_CONTR = ADC_POWER | ADC_SPEEDLL;
Delay1ms(2);
}
unsigned char GetADCResult(unsigned char ch){
ADC_CONTR = ADC_POWER | ADC_SPEEDLL | ch | ADC_START;
_nop_();
_nop_();
_nop_();
_nop_();
while( ! (ADC_CONTR & ADC_FLAG) );
ADC_CONTR &= ~ADC_FLAG;
return ADC_RES;
}
unsigned char DataSendPreprocess()
{
unsigned char i, t = 0;
bufsend[0] = 0x7f;
bufsend[1] = UPID;
bufsend[2] = MYID;
bufsend[3] = 3;
bufsend[4] = 0x13;
bufsend[5] = 0;
bufsend[6] = ( 255 - GetADCResult(0) )* 100 / 255 ;
for(i = 1; i <7; i ++ )
{
t ^= bufsend[i];
}
bufsend[7] = t;
bufsend[8] = 0xff;
return 9;
}
void DataSend(unsigned char ss[], unsigned char len)
{
unsigned char i;
for( i = 0; i < len; i ++ ){
SBUF = ss[i];
while( TI == 0 );
TI = 0;
}
}
void main()
{
unsigned char len;
InitADC();
UartInit();
while(1)
{
len = DataSendPreprocess();
DataSend(bufsend, len);
Delay1ms(1000);
}
}