目录
一、项目需求
二、仿真
三、程序
四、资料清单
资料下载地址:基于51单片机的自动浇花系统
一、项目需求
1、自动检测土壤湿度、温度、光照强度;
2、土壤湿度过低驱动水泵进行浇花;
3、LCD1602显示当前土壤湿度、温度、光照强度;
4、当光强、温度超过一定范围后报警;
二、仿真
三、程序
部分程序
enum { TEMP,HUMI };
typedef union //定义共用同类型
{unsigned int i;float f;
}value;int display = 0;
void delay(uchar ms)
{ // 延时子程序
uchar i;
while(ms--)
{ for(i = 0;i<250;i++);
}
}char ShtWriteByte(unsigned char value)
{unsigned char i,error=0;for(i=128;i>0;i>>=1) // 高位为1,循环右移{if (i&value)Data_P=1; // 和要发送的数相与,结果为发送的位elseData_P=0;Sck_P=1;_nop_(); // 延时3us_nop_();_nop_();Sck_P=0;}Data_P=1; // 释放数据线Sck_P=1;error=Data_P; // 检查应答信号,确认通讯正常_nop_();_nop_();_nop_();Sck_P=0;Data_P=1;return error; // error=1 通讯错误
}char ShtReadByte(unsigned char ack)
{unsigned char i,val=0;Data_P=1; // 释放数据线for(i=0x80;i>0;i>>=1) // 高位为1,循环右移{Sck_P=1;if(Data_P)val=(val|i); // 读一位数据线的值Sck_P=0;}Data_P=!ack; // 如果是校验,读取完后结束通讯Sck_P=1;_nop_(); // 延时3us_nop_();_nop_();Sck_P=0;_nop_();_nop_();_nop_();Data_P=1; // 释放数据线return val;
}void ShtTransStart(void)
{Data_P=1;Sck_P=0;_nop_();Sck_P=1;_nop_();Data_P=0;_nop_();Sck_P=0;_nop_();_nop_();_nop_();Sck_P=1;_nop_();Data_P=1;_nop_();Sck_P=0;
}void ShtConnectReset(void)
{unsigned char i;Data_P=1; //准备Sck_P=0;for(i=0;i<9;i++) //DATA保持高,SCK时钟触发9次,发送启动传输,通迅即复位{Sck_P=1;Sck_P=0;}ShtTransStart(); //启动传输
}char ShtMeasure(unsigned char *p_value, unsigned char *p_checksum, unsigned char mode)
{unsigned error=0;unsigned int i;ShtTransStart(); // 启动传输switch(mode) // 选择发送命令{case 1 : // 测量温度error+=ShtWriteByte(0x03);break;case 2 : // 测量湿度error+=ShtWriteByte(0x05);break;default:break;}for(i=0;i<65535;i++)if(Data_P==0)break; // 等待测量结束if(Data_P)error+=1; // 如果长时间数据线没有拉低,说明测量错误*(p_value) =ShtReadByte(1); // 读第一个字节,高字节 (MSB)*(p_value+1)=ShtReadByte(1); // 读第二个字节,低字节 (LSB)*p_checksum =ShtReadByte(0); // read CRC校验码return error; // error=1 通讯错误
}void CalcSHT11(float *p_humidity ,float *p_temperature)
{const float C1=-4.0; // 12位湿度精度 修正公式const float C2=+0.0405; // 12位湿度精度 修正公式const float C3=-0.0000028; // 12位湿度精度 修正公式const float T1=+0.01; // 14位温度精度 5V条件 修正公式const float T2=+0.00008; // 14位温度精度 5V条件 修正公式float rh=*p_humidity; // rh: 12位 湿度float t=*p_temperature; // t: 14位 温度float rh_lin; // rh_lin: 湿度 linear值float rh_true; // rh_true: 湿度 ture值float t_C; // t_C : 温度 ℃t_C=t*0.01 - 40; //补偿温度rh_lin=C3*rh*rh + C2*rh + C1; //相对湿度非线性补偿rh_true=(t_C-25)*(T1+T2*rh)+rh_lin; //相对湿度对于温度依赖性补偿*p_temperature=t_C; //返回温度结果*p_humidity=rh_true; //返回湿度结果
}