Temperature Controlled Greenhouse using a Fan

From Sensors in Schools
Jump to navigation Jump to search

Temperature Controlled Greenhouse using a Fan


Close up of Arduino circuit


Arduino code - Two temperature sensors

  • DHT22 - temperature and humidity sensor
  • Onewire temperature sensor

Arduino code

/* How to use the DHT-22 temperature and humidity sensor
   and Onewire temperature sensor with Arduino Uno
*/

//Libraries
#include <DHT.h>;
#include <OneWire.h>
#include <DallasTemperature.h>

// Data wire is conntec to the Arduino digital pin 4
#define ONE_WIRE_BUS 4

// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature sensor 
DallasTemperature soil_temp(&oneWire);

//Constants
#define DHTPIN 7     // what pin we're connected to
#define DHTTYPE DHT22   // DHT 22  (AM2302)
DHT dht(DHTPIN, DHTTYPE); //// Initialize DHT sensor for normal 16mhz Arduino


//Variables
float hum;  //Stores humidity value
float air_temp; //Stores temperature value

void setup()
{
  Serial.begin(9600);
  dht.begin();
  soil_temp.begin();
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
}

void loop()
{
    delay(2000);  //Delay 2 seconds
    // Read oneWire temperature sensor
    // Call sensors.requestTemperatures() to issue a global temperature and Requests to all devices on the bus
    soil_temp.requestTemperatures(); 
    Serial.print(soil_temp.getTempCByIndex(0)); 
    Serial.print(",");
    
    //Read data and store it to variables hum and temp - DHT22 
    hum = dht.readHumidity();
    air_temp = dht.readTemperature();
    Serial.print(hum);
    Serial.print(",");
    Serial.println(air_temp);

    if (air_temp > 25.0) {
      //turn on fan to cool greenhouse
      digitalWrite(13, HIGH);  // turn fan ON
    }
    else {
      digitalWrite(13, LOW);  // turn fan OFF
    }
    delay(300000);  // sleep for 5 minutes
}

Python code

#!/usr/bin/env python3
# dweet data
import serial
import datetime
import plotly
import plotly.graph_objects as go
import pandas
import time
import requests

if __name__ == '__main__':
    ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
    ser.reset_input_buffer()
    while True:
        time.sleep(0.1)
        if ser.in_waiting > 0:
            line = ser.readline().decode('utf-8').rstrip()
            print(f"Data separated using commas {line.split(',')}")
            mylist = line.split(',')
            try:
                soil_temp = float(mylist[0])
                humid = float(mylist[1])
                air_temp = float(mylist[2])
            except:
                soil_temp = 0.0
                humid = 0.0
                air_temp = 0.0

            time.sleep(1)
            now = datetime.datetime.now()
            datetime_stamp = now.strftime("%Y-%m-%d %H:%M:%S")
            data = datetime_stamp + "," + str(soil_temp) + "," + str(humid) + "," + str(air_temp) + "\n"
            print(f'The data is =  {data}')

            f = open('/home/pi/auto-greenhouse/greenhouse_data.txt','a')
            f.write(data)
            f.close()
            print("Data saved")
            
            # import and plot data text file
            df = pandas.read_csv('/home/pi/auto-greenhouse/greenhouse_data.txt')

            fig = go.Figure(data = go.Scatter(mode='markers',
                                                x=df.date_time,
                                                y=df.air_temp,
                                                marker=dict(
                                                    color="LightSkyBlue",
                                                    size=20)
                                                )
                                        )
            fig.update_layout(title="Air Temperature in Greenhouse",
                                xaxis_title = 'Time',
                                yaxis_title = 'Air temperature',
                                font=dict(
                                    size=20,
                                    color="RebeccaPurple"
                                )
                            )

            plotly.offline.plot(fig,
                                filename="/home/pi/auto-greenhouse/air_temperature_plot.html",
                                auto_open=False)

            print("Air temperature data plotted")
            
            
            fig = go.Figure(data = go.Scatter(mode='markers',
                                                x=df.date_time,
                                                y=df.soil_temp,
                                                marker=dict(
                                                    color="LightSkyBlue",
                                                    size=20)
                                                )
                                        )
            fig.update_layout(title="Soil Temperature in Greenhouse",
                                xaxis_title = 'Time',
                                yaxis_title = 'Temperature',
                                font=dict(
                                    size=20,
                                    color="RebeccaPurple"
                                )
                            )

            plotly.offline.plot(fig,
                                filename="/home/pi/auto-greenhouse/soil_temperature_plot.html",
                                auto_open=False)

            print("Soil Temperature data plotted")
            
            try:
                print("Preparing dweet")
                dweet_dict = {}
                dweet_dict.update({"soil_temp": str(soil_temp)})
                dweet_dict.update({"humidity": str(humid)})
                dweet_dict.update({"air_temp": str(air_temp)})
                dweet_dict.update({"last_updated": str(datetime_stamp)})
                url = "https://dweet.io/dweet/for/MPPS-auto-greenhouse-Aug2023?"
                x = requests.post(url, json=dweet_dict)
                print(x.text)
            except:
                print("Dweet failed")
            # check dweet with - https://dweet.io/get/latest/dweet/for/<dweet-name-here>


Arduino Code - One temperature sensor - DHT22

Arduino Code

/* How to use the DHT-22 temperature and humidity sensor
   with Arduino Uno
*/

//Libraries
#include <DHT.h>;

//Constants
#define DHTPIN 7     // what pin we're connected to
#define DHTTYPE DHT22   // DHT 22  (AM2302)
DHT dht(DHTPIN, DHTTYPE); //// Initialize DHT sensor for normal 16mhz Arduino

//Variables
float hum;  //Stores humidity value
float air_temp; //Stores temperature value

void setup()
{
  Serial.begin(9600);
  dht.begin();
  pinMode(13, OUTPUT);  // controls Fan
  digitalWrite(13, LOW);  // Fan off
}

void loop()
{
    hum = dht.readHumidity();
    air_temp = dht.readTemperature();
    Serial.print(hum);
    Serial.print(",");
    Serial.println(air_temp);

    if (air_temp > 25.0) {
      //turn on fan to cool greenhouse
      digitalWrite(13, HIGH);  // turn fan ON
    }
    else {
      digitalWrite(13, LOW);  // turn fan OFF
    }
    delay(300000);
}


Python Code

#!/usr/bin/env python3
# dweet data
import serial
import datetime
import plotly
import plotly.graph_objects as go
import pandas
import time
import requests

if __name__ == '__main__':
    ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
    ser.reset_input_buffer()
    while True:
        time.sleep(0.1)
        if ser.in_waiting > 0:
            line = ser.readline().decode('utf-8').rstrip()
            print(f"Data separated using commas {line.split(',')}")
            mylist = line.split(',')
            try:
                humid = float(mylist[0])
                air_temp = float(mylist[1])
            except:
                humid = 0.0
                air_temp = 0.0

            time.sleep(1)
            now = datetime.datetime.now()
            datetime_stamp = now.strftime("%Y-%m-%d %H:%M:%S")
            data = datetime_stamp + "," + str(humid) + "," + str(air_temp) + "\n"
            print(f'The data is =  {data}')

            f = open('/home/pi/auto-greenhouse/greenhouse_data.txt','a')
            f.write(data)
            f.close()
            print("Data saved")
            
            # import and plot data text file
            df = pandas.read_csv('/home/pi/auto-greenhouse/greenhouse_data.txt')

            fig = go.Figure(data = go.Scatter(mode='markers',
                                                x=df.date_time,
                                                y=df.air_temp,
                                                marker=dict(
                                                    color="LightSkyBlue",
                                                    size=20)
                                                )
                                        )
            fig.update_layout(title="Air Temperature in Greenhouse",
                                xaxis_title = 'Time',
                                yaxis_title = 'Air temperature',
                                font=dict(
                                    size=20,
                                    color="RebeccaPurple"
                                )
                            )

            plotly.offline.plot(fig,
                                filename="/home/pi/auto-greenhouse/air_temperature_plot.html",
                                auto_open=False)

            print("Air temperature data plotted")
            
            
            fig = go.Figure(data = go.Scatter(mode='markers',
                                                x=df.date_time,
                                                y=df.humidity,
                                                marker=dict(
                                                    color="LightSkyBlue",
                                                    size=20)
                                                )
                                        )
            fig.update_layout(title="Humidity in Greenhouse",
                                xaxis_title = 'Time',
                                yaxis_title = 'Humidity',
                                font=dict(
                                    size=20,
                                    color="RebeccaPurple"
                                )
                            )

            plotly.offline.plot(fig,
                                filename="/home/pi/auto-greenhouse/humidity_data_plot.html",
                                auto_open=False)

            print("Greenhouse humidity data plotted")
            
            try:
                print("Preparing dweet")
                dweet_dict = {}
                dweet_dict.update({"humidity": str(humid)})
                dweet_dict.update({"air_temp": str(air_temp)})
                dweet_dict.update({"last_updated": str(datetime_stamp)})
                url = "https://dweet.io/dweet/for/MPPS-auto-greenhouse-Aug2023?"
                x = requests.post(url, json=dweet_dict)
                print(x.text)
            except:
                print("Dweet failed")
            # check dweet with - https://dweet.io/get/latest/dweet/for/<dweet-name-here>