#include "DHT.h"
#include <Servo.h>
#include "pitches.h"
//农场设备
#define pfs 2//排风扇 使用白色led表示
#define jrq 3//加热器 使用红色led表示
#define dg 4 //滴灌 使用淡蓝led表示
#define pg 5 //喷灌 使用蓝色led表示
#define bcd 6//白炽灯 使用黄色led表示
#define csj 7//抽水机 使用紫色led表示
#define ny 9//农药阀门
#define fl 10//肥料阀门
#define zgp 11//遮光棚
//农场监测
#define DHTPIN 8//温度湿度监测
#define swgz A1//室外光照
#define sljz A2//水量监测
//安全警报
#define wdjb 12//温度警报
#define sljb 13//水量警报
#define button1 A3//农药按钮
#define button2 A4//肥料按钮
//目标数值
const int wd=25;//设定温度
const int sd=65;//设定湿度
const int gz=500;//设定光照强度
const int slmix=200;//水量最低
const int slmax=800;//水量最高
int nyflag=0;
int flflag=0;
const float GAMMA = 0.7;
const float RL10 = 50;
const int gameTones[] = { NOTE_G3, NOTE_C4, NOTE_E4, NOTE_G5};
DHT dht(DHTPIN, DHT22);//温度湿度
Servo myservo1;//遮光棚
Servo myservo2;//农药阀门
Servo myservo3;//肥料阀门
void setup() {
for(int i=2;i<=7;i++){
pinMode(i, OUTPUT);
}
myservo1.attach(ny);
myservo2.attach(fl);
myservo3.attach(zgp);
dht.begin();
pinMode(button1, INPUT);
pinMode(button2, INPUT);
}
void loop() {
//湿度监控
while(dht.readHumidity()<=sd){//是否缺水
digitalWrite(dg, HIGH);//打开滴灌
digitalWrite(pg, HIGH);//打开喷灌
delay(1000);
}
digitalWrite(dg, LOW);
digitalWrite(pg, LOW);
//温度监控
while(dht.readTemperature()<=wd-1||dht.readTemperature()>=wd+1){//温度是否合适
if(dht.readTemperature()<=10||dht.readTemperature()>=50){
tone(wdjb,gameTones[1]);
}else{
noTone(wdjb);
}
digitalWrite(pfs,HIGH);//打开排风扇
if(dht.readTemperature()<=wd-1){
digitalWrite(jrq, HIGH);//打开加热器
}
delay(1000);
}
digitalWrite(pfs, LOW);
digitalWrite(jrq, LOW);
//光强监控
int analogValue = analogRead(swgz);
float voltage = analogValue / 1024. * 5;
float resistance = 2000 * voltage / (1 - voltage / 5);
float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
if(lux<=gz){//光照强度不足
myservo3.write(180);//关闭遮光棚
digitalWrite(6, HIGH);//打开白炽灯
}
else{
myservo3.write(0);//打开遮光棚
digitalWrite(6, LOW);//关闭白炽灯
}
//水量监控,抽水
if(analogRead(sljz)<=slmix){
digitalWrite(csj, HIGH);
}
if(analogRead(sljz)>=slmax){
digitalWrite(csj, LOW);
}
if(analogRead(sljz)<=50||analogRead(sljz)>=950){
tone(sljb,gameTones[0]);
}else{
noTone(sljb);
}
//农药喷洒
if(digitalRead(button1)==HIGH){
nyflag=abs(nyflag-1);
}
if(nyflag==1){
myservo1.write(0);
digitalWrite(pg, HIGH);
}else{
myservo1.write(180);
digitalWrite(pg,LOW);
}
//肥料滴灌
if(digitalRead(button2)==HIGH){
flflag=abs(flflag-1);
}
if(flflag==1){
myservo2.write(0);
digitalWrite(dg, HIGH);
}else{
myservo2.write(180);
digitalWrite(dg,LOW);
}
}