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) //@11.0592MHz
{
unsigned char i, j;
while( x -- ){
_nop_();
_nop_();
_nop_();
i = 11;
j = 190;
do
{
while (--j);
} while (--i);
}
}
void UartInit() // 9600 @11.0592
{
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; //传感器类型0x13---->土壤湿度
bufsend[5] = 0; //数据高字节
bufsend[6] = ( 255 - GetADCResult(0) )* 100 / 255 ; //AD通道号0转换后的数据
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);
}
}
来源:CSDN
作者:_Hello Spring
链接:https://blog.csdn.net/wct3344142/article/details/103804480