Arduino Uno Example Projects for Students: Difference between revisions

From Sensors in Schools
Jump to navigation Jump to search
 
(27 intermediate revisions by the same user not shown)
Line 206: Line 206:
= Temperature Controlled Greenhouse Project =
= Temperature Controlled Greenhouse Project =


== How does a Greenhouse Work and why does it get so warm? ==
== How does a Greenhouse work and why does it get so warm? ==


A greenhouse is warm because it is designed to trap heat and create a favorable environment for growing plants. A greenhouse works by allowing sunlight to enter the structure and then trapping the heat that is generated by the absorption of sunlight.
A greenhouse is warm because it is designed to trap heat and create a favorable environment for growing plants. A greenhouse works by allowing sunlight to enter the structure and then trapping the heat that is generated by the absorption of sunlight.
Line 234: Line 234:


In summary, several techniques can be used to cool greenhouses, including natural ventilation, shade cloth, evaporative cooling, fans, air conditioning, and thermal mass. The method or combination of methods used will depend on the size and design of the greenhouse, as well as the climate and temperature conditions in the local area.
In summary, several techniques can be used to cool greenhouses, including natural ventilation, shade cloth, evaporative cooling, fans, air conditioning, and thermal mass. The method or combination of methods used will depend on the size and design of the greenhouse, as well as the climate and temperature conditions in the local area.
== Temperature Controlled Greenhouse using Solar powered Electric Fans ==
* In this project a DHT22 Temperature and Humidity sensor will be used to monitor the internal temperature of the greenhouse.
* If the greenhouse exceeds 25degC then a Solar powered fan will be used to cool the greenhouse.
== Fritzing Circuit Diagram ==
* Parts required:
** '''80mm 12V DC Fan''' - [https://www.jaycar.com.au/80mm-12v-dc-fan/p/YX2512? Jaycar]
** '''12V 5W Solar Panel''' - [https://www.jaycar.com.au/12v-5w-solar-panel-with-clips/p/ZM9050? Jaycar]
** '''Pololu Basic SPDT Relay Carrier with 5VDC Relay''' - [https://core-electronics.com.au/pololu-basic-spdt-relay-carrier-with-5vdc-relay-assembled.html Core Electronics or Jaycar]
** '''DHT22 Temperature and Relative Humidity Sensor Module''' - [https://core-electronics.com.au/dht22-temperature-and-relative-humidity-sensor-module.html Core Electronics or Jaycar]
[[File:Screenshot 2023-05-05 at 7.12.51 am.png | 900px]]
== Arduino Uno Code Example ==
<syntaxhighlight lang="c++">
/* How to use the DHT-22 Temperature and humidity sensor with Arduino uno to control the temperature of a Greenhouse
  If the temperature is greater than 25 degC the relay (and fan) will turn on to cool the greenhouse
  The fan is powered using a 12V 5 Watt Solar PV Panel
*/
//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
int chk;
float hum;  //Stores humidity value
float temp; //Stores temperature value
void setup()
{
  Serial.begin(9600);
  dht.begin();
  pinMode(5, OUTPUT); // Set pin 5 to control relay
}
void loop()
{
    delay(2000);
    //Read data and store it to variables hum and temp
    hum = dht.readHumidity();
    temp= dht.readTemperature();
    //Print temp and humidity values to serial monitor
    Serial.print("Humidity: ");
    Serial.print(hum);
    Serial.print(" %, Temp: ");
    Serial.print(temp);
    Serial.println(" Celsius");
    if (temp >= 25){
      digitalWrite(13, HIGH);  // turn relay on - which will turn fan on.
      Serial.println("Fan on because Greenhouse is too hot");
    }
    else {
      digitalWrite(13, LOW);  //turn relay off.
      Serial.println("Fan is Off");
    }
    delay(10000); //Delay 10 seconds.
}
</syntaxhighlight>
== Arduino Code Example showing output in Serial Monitor ==
[[File:Screenshot 2023-05-05 at 7.37.44 am.png | 900px]]
= Smart Tank - Water Level sensor and Water Pump =
* A smart tanks is able to read 7 day rain weather forecasts from the Bureau of Meteorology and to use this information to adjust the amount of water stored in a rainwater tank.
* If a large rain event is forecast, the smart tank will empty the rainwater tank.
* Rain tank water is normally used to irrigate the garden.
* The smart tank can also monitor for extreme heat days and also apply water to the garden to help plants transpire.
== STEM Lab experiment and Control Logic ==
* In this experiment we will enter our own Bureau of Meteorology rain data to control the operation of the smart tank.
* Rain data will represent rain forecasts for the following day (24 hour forecast).
* Rain water tank water levels will be constantly measured using ultrasonic distance sensor.
* In this example the operation of the smart tank will be kept simple.
** If rain event is '''0mm''' - Pump will turn off.
** If rain event is '''1-20mm''' - Pump will turn on.
** If rain event is '''20-60mm''' - Pump will turn on.
* Rain tank levels will be signalled using hand gestures (simulation of water levels in  rainwater tank)
== Parts list ==
* [https://core-electronics.com.au/hc-sr04-ultrasonic-module-distance-measuring-sensor.html HC-SR04 Ultrasonic Module Distance Measuring Sensor]
* [https://core-electronics.com.au/peristaltic-liquid-pump-with-silicone-tubing-5v-to-6v-dc-power.html Peristaltic Liquid Pump with Silicone Tubing - 5V to 6V DC Power]
* [https://core-electronics.com.au/raspberry-pi-3-power-supply.html Raspberry Pi 3+ Power Supply (Official)]
* [https://core-electronics.com.au/pololu-basic-spdt-relay-carrier-with-5vdc-relay-assembled.html Pololu Basic SPDT Relay Carrier with 5VDC Relay (Assembled)]
== Calibrate Max and Min values for Distance Sensor ==
* Build the distance sensor circuit from [http://www.waterwaysinwhittlesea.org/index.php/Arduino_Uno_Introduction#Arduino_Uno_-_Connect_a_Distance_Sensor_to_an_Arduino_Uno Distance Sensor Project]
* Upload the code below and measure the maximum and minimum values for the distance sensor.
<syntaxhighlight lang="c++">
#define trigPin 10
#define echoPin 13
void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}
void loop() {
  float duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
 
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) * 0.0344;
 
  if (distance >= 400 || distance <= 2){
    Serial.print("Distance = ");
    Serial.println("Out of range");
  }
  else {
    Serial.print("Distance = ");
    Serial.print(distance);
    Serial.println(" cm");
    delay(500);
  }
  delay(500);
}
</syntaxhighlight>
== Example distance sensor outputs during calibration ==
* Use hand gestures to mimic rain water tank water level ranges.
* In this data set the maximum value is 18cm and the minimum value is 4cm.
[[File:Screenshot 2023-05-30 at 4.19.54 am.png | 900px]]
== Send the Arduino Uno rain data using the Serial Monitor ==
* The '''Serial Monitor''' can display data from the Arduino Uno and also send data to the Arduino Uno.
* Data can be sent using the '''input bar''' at the top of the Serial Monitor.
* Enter a value from 0 to 60 and then press '''Enter''' or click on the '''Send''' button to send the value to the Arduino Uno.
* In this example we will send predicted rainfall data to the Arduino Uno.
[[File:Screenshot 2023-05-30 at 5.34.26 am.png | 900px]]
== Arduino Uno code to send rain forecast ==
<syntaxhighlight lang="c++">
/* Sending simulated rain forecast data to the Arduino Uno
*/
String rain_string;
int rain_integer;
// the setup function runs once when you press reset or power the board
void setup() {
  Serial.begin(9600);
  Serial.println("Enter the amount of predicted rain from 0 to 60mm");
}
// the loop function runs over and over again forever
void loop() {
  delay(500);
  if(Serial.available()){
        rain_string = Serial.readStringUntil('\n');
        rain_integer = rain_string.toInt();            // convert String to integer
       
        if(rain_integer == 0){
            Serial.println("No rain is forecast");
        }
        else if(rain_integer >=1 && rain_integer <= 20){
            Serial.print("Modest rain (mm) predicted ");
            Serial.println(rain_integer);
        }
        else if(rain_integer >20 && rain_integer <=60){
            Serial.print("Large rain (mm) event predicted: ");
            Serial.println(rain_integer);
        }
    }
}
</syntaxhighlight>
== Example output of rain forecast ==
[[File:Screenshot 2023-05-30 at 4.42.10 am.png | 900px]]
== Adding Relay Control for Water pump ==
* A relay will control a peristaltic water pump.
* The pump will be powered using a 5V power supply.
* The relay will be controlled using Arduino Uno '''Pin 12'''
== Fritzing - Circuit Diagram showing Distance sensor and Relay ==
[[File:Screenshot 2023-05-30 at 5.30.22 am.png | 900px]]
== Arduino Uno code ==
<syntaxhighlight lang="c++">
/* Sending simulated rain forecast data to the Arduino Uno
* If tank is too full a peristaltic pump controlled using Pin 12 will empty the tank
* Tank water level is measured using a distance sensor
* Hand gestures will simulate tank levels
*/
#define trigPin 10
#define pump 12
#define echoPin 13
String rain_string;
int rain_integer = 0;
// the setup function runs once when you press reset or power the board
void setup() {
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(pump, OUTPUT);
  Serial.println("Enter the amount of predicted rain from 0 to 60mm");
}
// the loop function runs over and over again forever
void loop() {
  //  *** Measure water level using distance sensor ***
  float duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
 
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) * 0.0344;
    if (distance >= 400 || distance <= 2){
    Serial.print("Distance = ");
    Serial.println("Out of range");
  }
  else {
    Serial.print("Distance = ");
    Serial.print(distance);
    Serial.println(" cm");
    delay(500);
  }
 
  delay(1000);
  // *** Read rain forecast data using input from the Serial Monitor ***
  if(Serial.available()){
        rain_string = Serial.readStringUntil('\n');
        rain_integer = rain_string.toInt();            // convert String to integer
       
        if(rain_integer == 0){
            Serial.println("No rain is forecast.");
            Serial.println("Turning pump OFF");
            digitalWrite(pump, LOW);
           
        }
        else if(rain_integer >=1 && rain_integer <= 20){
            Serial.print("Modest rain (mm) predicted: ");
            Serial.println(rain_integer);
            Serial.println("Turning pump ON");
            digitalWrite(pump, HIGH);
        }
        else if(rain_integer >20 && rain_integer <=60){
            Serial.print("Large rain (mm) event predicted: ");
            Serial.println(rain_integer);
            Serial.println("Turning pump ON");
            digitalWrite(pump, HIGH);
        }
    }
}
</syntaxhighlight>
== Example output of Smart Tank code ==
[[File:Screenshot 2023-05-30 at 5.15.25 am.png | 900px]]

Latest revision as of 19:37, 29 May 2023

Solar Distillation - Water Purification project

Solar Distillation and the production of Drinking Water

  • Solar distillation is a process of purifying water by using the sun's energy to evaporate water and condense the resulting vapor into a clean container. It is a simple, effective and sustainable method of producing safe drinking water, especially in regions where clean water sources are scarce.
  • The process of solar distillation involves the use of a solar still, which is a device that consists of a shallow basin or pit covered with a transparent material such as glass or plastic. The basin is filled with contaminated water, and the sun's rays heat the water, causing it to evaporate. The water vapor then rises and condenses on the cooler surface of the transparent cover, which is angled to allow the condensate to flow into a collection container.
  • To make drinking water using solar distillation, the following steps can be followed:
    • Build or acquire a solar still: A solar still can be made using simple materials such as glass or plastic sheets, wood, and metal. Alternatively, pre-built solar stills can be purchased from manufacturers.
    • Place the solar still in a sunny location: The solar still should be placed in a location where it receives maximum sunlight exposure throughout the day.
    • Fill the still with contaminated water: The contaminated water is poured into the basin of the still.
    • Cover the still with a transparent material: The basin is covered with a transparent material such as glass or plastic, which allows sunlight to enter and heat the water.
    • Wait for the water to evaporate and condense: As the water is heated by the sun, it evaporates and rises to the surface of the transparent cover, where it condenses and drips into a collection container.
    • Collect the clean water: The condensed water that drips into the collection container is clean and safe for drinking.

Overall, solar distillation is a simple and effective method of producing safe drinking water using the sun's energy. It is particularly useful in remote or arid regions where access to clean water is limited.

Solar Distillation using a Solar Thermal Collector Panel

  • In this Solar Distillation experiment a flat panel is used to distill the water.
  • The Solar Distillation panel covered by a black felt mat to maximise heat gain and also slow down the fall of water on the panel.
  • The Panel is also covered by a transparent sheet of plastic drawn taught over the panel, that allows sunlight to pass through, and that also collects droplets of distilled water.
  • Dirty water is pumped to the top of the panel.
  • As the dirty water falls down the length of the panel (by gravity) it heats up and some of the water evaporates.
  • The evaporated water condenses on the inside surface of the clear plastic film of plastic. Once the water droplets ae big enough they will trickle down the inside surface as small rivulets of water.
  • Dirty water is collected at the base of the panel and is returned to the main dirty water tank.
  • Purified water is collected as runoff from the plastic film and is collected in a drinking water tank.

Fritzing Circuit Diagram

  • Parts required:
    • Relay - Pololu Basic SPDT Relay Carrier with 5VDC to control pump. Relay controlled using pin 12 on Arduino. Core Electronics
    • Peristaltic pump - Peristaltic Liquid Pump with Silicone Tubing - 5V to 6V DC Power Core Electronics
    • LED - to indicate status of pump. LED controlled using pin 13 on Arduino.
    • 5V supply - using a Raspberry Pi 3+ Power Supply Core Electronics
    • 5 Amp Fuse - 5A M205 Quick Blow Fuse Jaycar
    • Fuse Holder - Heavy Duty 20A 3AG Inline Fuse Holder (20 Amps, 3AG indicates thickness of leads) Jaycar

Arduino Code Example

  • This code example will demonstrate how to control a peristaltic pump using a relay.
  • After executing the code open the Serial Monitor.
  • To run the pump (turn relay on) enter the command ON and then press the Enter key.
  • To turn the pump off enter the command OFF and then press the Enter key.
  • To understand more about Serial communication from your computer to the Arduino see this Tutorial Arduino Tutorial Serial Inputs
/* Solar Distillation project with Arduino Uno
   Using the Arduino to control a relay (and peristaltic pump). Relay is controlled on Pin 12
   Pump on is signaled using an LED connected to Pin 13
   Relay is turned on and off using commands sent via the Serial Monitor
   ON - turn relay on
   OFF - turn relay off
*/

String command;

// the setup function runs once when you press reset or power the board
void setup() {
  Serial.begin(9600);
  // initialize digital pins as output.
  pinMode(13, OUTPUT); //  LED
  pinMode(12, OUTPUT); // relay
}

// the loop function runs over and over again forever
void loop() {
  delay(500);
  if(Serial.available()){
        command = Serial.readStringUntil('\n');
         
        if(command.equals("ON")){
            digitalWrite(13, HIGH); // turn LED on
            digitalWrite(12, HIGH); // turn relay on
            Serial.println("Relay is now ON");
        }
        else if(command.equals("OFF")){
            digitalWrite(13, LOW); // turn LED off
            digitalWrite(12, LOW); // turn relay off
            Serial.println("Relay is now OFF");
        }
    }
}

Arduino Code - Example of operation

  • After uploading the code (sketch) to the Arduino Uno, click on the Serial Monitor button (top right of Arduino IDE)
  • You can now enter commands from your computer to the Arduino.
  • After a command is entered click Send or press the Enter key.



Solar PV Panel with Servo Scanning

Operation of a Solar PV Panel

A solar photovoltaic (PV) panel works by converting sunlight into direct current (DC) electricity. The panel consists of multiple solar cells made from semiconductor materials, usually silicon, which are connected together.

When sunlight hits the surface of the solar cells, it excites the electrons in the semiconductor material, causing them to move. This movement of electrons creates a flow of electricity, which can be captured by the panel and used to power electrical devices.

The solar cells are arranged in a grid pattern and wired together to form a module. Multiple modules can then be connected together to form a solar panel, which can generate more electricity.

The amount of electricity generated by a solar panel depends on several factors, including the amount of sunlight it receives, the efficiency of the solar cells, and the temperature of the panel. A solar panel typically generates more electricity in direct sunlight and at cooler temperatures.

Any excess electricity produced by a solar panel can be stored in batteries or fed back into the grid for others to use.

What is a Servo Motor and how does it work using Pulse Width Modulation

A servo motor is a type of motor that is used for precise control of position. It is commonly used in robotics, automation, and other applications where precise motion control is needed.

A servo motor works by receiving a control signal that specifies the desired position. The control signal sent to the servo motor is typically a pulse-width modulation (PWM) signal. PWM is a technique used to encode a message into a pulsing signal. In the case of servo motors, the PWM signal encodes the desired position of the servo.

Most hobby servos use a pulse that lasts between 1 millisecond and 2 milliseconds to tell it how much to turn. A 1 millisecond pulse means that the servo shaft is turned all the way to the left, usually called the 0 degree position. A 2 millisecond pulse tells the servo to turn all the way to the right, the 180 degree position. A 1.5 millisecond pulse would send the servo to the neutral or middle position.

Hobby servos have a built-in feedback mechanism, typically in the form of a potentiometer, that provides information on the current position of the motor. The motor adjusts its output shaft until the feedback signal matches the desired position or speed specified by the PWM signal.

In summary, a servo motor works by receiving a PWM control signal that specifies the desired position or speed of the motor. The motor uses the control signal and feedback mechanism to adjust its output shaft to move to the desired position.

Fritzing - Circuit Diagram for Hobby Servo Motor

  • Parts required:
    • Adafruit Motor/Stepper/Servo Shield for Arduino Core Electronics
    • 0.5W Solar Panel 55mm x 70mm (Seeed Studio) Core Electronics
    • Standard Hobby Servo (10kg/cm) - any servo will do but servos with metal gears will last longer. You can also buy water proof servos Core Electronics
    • 2 x 10,000 Ohm High Precision resistors Mouser Electronics


Arduino Code Example

/*
 Sun Tracker project
 Servo motor with solar PV panel attached
 Will find sunniest location and stay there for 1 minute
 Then will sweep again to find next sunniest position (sun will move during the day)
*/

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
int servoPosition = 0; 
int sunniestServoPosition = 0;
int sunniestSolarValue = 0;
int solarPin = A2;    // select the input pin for the potentiometer
int solarValue = 0;  // variable to store the value coming from the sensor
int count = 0;      // counter 

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  Serial.begin(9600);
}

void loop() {
    for (servoPosition = 20; servoPosition <= 170; servoPosition += 10) { 
        // servo goes from 0 degrees to 180 degrees - but values 0 and 180 cause servo to gitter
        // so instead the range will be from 20 to 170
       // in steps of 10 degree
       myservo.write(servoPosition);      // tell servo to go to position in variable 'pos'
       Serial.print("The current servo position is ");
       Serial.println(servoPosition);
       delay(200);                       // wait for 0.2 seconds for the servo to reach position
       
       // read the value from the solar PV panel on Analog Pin A2:
       // analog pin returns reads 0-5V by returning a value between 0 and 1023
       solarValue = analogRead(solarPin);
       Serial.print("The solarValue is ");
       Serial.println(solarValue);

       // Check to see if servo has found a new sunniest location
       // If location is sunnier then store this servoPosition value
       if (solarValue > sunniestSolarValue){
         sunniestSolarValue = solarValue;
         sunniestServoPosition = servoPosition;
         Serial.print("We have a new sunniest location! ");
         Serial.println(servoPosition);
       }
    }

    // goto Sunniest Position and wait there for 1 minute
    Serial.print("Going to sunniest position ");
    Serial.print(sunniestServoPosition);
    Serial.println(" for 1 minute ");
    myservo.write(sunniestServoPosition);
    
    // waits in sunniest position for 1 minute
    for (count = 0; count <= 60; count += 10) { 
       Serial.print("Counting to 60 - ");
       Serial.println(count);
       delay(10000); // 10 seconds each loop 
    }                     
}

Arduino Code Example of Operation using Serial Monitor

Temperature Controlled Greenhouse Project

How does a Greenhouse work and why does it get so warm?

A greenhouse is warm because it is designed to trap heat and create a favorable environment for growing plants. A greenhouse works by allowing sunlight to enter the structure and then trapping the heat that is generated by the absorption of sunlight.

Sunlight consists of various wavelengths, including visible light and infrared radiation. When sunlight enters a greenhouse, it passes through the glass or plastic walls and is absorbed by the plants, soil, and other materials inside. As these materials absorb the sunlight, they become warmer and begin to radiate heat back into the greenhouse.

The glass or plastic walls of a greenhouse are designed to allow sunlight to pass through but prevent the heat from escaping. This is because glass and plastic are good at transmitting visible light but poor at transmitting infrared radiation, which is the type of radiation that is responsible for heat transfer.

In addition to trapping heat, a greenhouse also creates a humid environment, which can further promote plant growth. As plants transpire, they release moisture into the air, which can increase the humidity levels inside the greenhouse. This can help to create a more favorable environment for plant growth, especially in arid or dry regions.

In summary, a greenhouse is warm because it is designed to trap heat and create a favorable environment for growing plants. The glass or plastic walls of a greenhouse allow sunlight to enter but prevent the heat from escaping, creating a warm and humid environment that is ideal for plant growth.

What methods are used to Cool Greenhouses?

Greenhouses can become too warm, especially during hot weather or when they receive too much direct sunlight. To cool greenhouses and maintain a suitable growing environment for plants, several techniques can be used. Here are some common methods for cooling greenhouses:

  • Natural ventilation: One of the most common methods for cooling greenhouses is natural ventilation, which involves opening windows, vents, or doors to allow cooler air to enter the greenhouse and warm air to escape. Natural ventilation can be effective when the outside temperature is lower than the inside temperature.
  • Shade cloth: Shade cloth is a type of mesh material that is installed above the greenhouse to reduce the amount of direct sunlight that enters. By shading the greenhouse, less heat is absorbed by the plants and materials inside, which can help to keep the greenhouse cooler.
  • Evaporative cooling: Evaporative cooling involves using water to lower the temperature and increase the humidity inside the greenhouse. This can be done by installing misting systems or evaporative coolers that spray water into the air. As the water evaporates, it absorbs heat from the air, which can help to cool the greenhouse.
  • Fans: Fans can be used to circulate air inside the greenhouse and create a cooling breeze. This can be particularly effective when used in conjunction with natural ventilation or evaporative cooling.
  • Air conditioning: In some cases, air conditioning units can be used to cool greenhouses. This is more common in large commercial greenhouses that require precise temperature control.
  • Thermal mass: Thermal mass refers to the ability of materials to absorb and store heat. By incorporating thermal mass materials, such as water barrels or concrete floors, into the greenhouse design, the heat generated by the plants and materials inside can be stored and released at a later time, helping to regulate temperature and cool the greenhouse.

In summary, several techniques can be used to cool greenhouses, including natural ventilation, shade cloth, evaporative cooling, fans, air conditioning, and thermal mass. The method or combination of methods used will depend on the size and design of the greenhouse, as well as the climate and temperature conditions in the local area.

Temperature Controlled Greenhouse using Solar powered Electric Fans

  • In this project a DHT22 Temperature and Humidity sensor will be used to monitor the internal temperature of the greenhouse.
  • If the greenhouse exceeds 25degC then a Solar powered fan will be used to cool the greenhouse.

Fritzing Circuit Diagram

Arduino Uno Code Example

/* How to use the DHT-22 Temperature and humidity sensor with Arduino uno to control the temperature of a Greenhouse
   If the temperature is greater than 25 degC the relay (and fan) will turn on to cool the greenhouse
   The fan is powered using a 12V 5 Watt Solar PV Panel
*/

//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
int chk;
float hum;  //Stores humidity value
float temp; //Stores temperature value

void setup()
{
  Serial.begin(9600);
  dht.begin();
  pinMode(5, OUTPUT); // Set pin 5 to control relay
}

void loop()
{
    delay(2000);
    //Read data and store it to variables hum and temp
    hum = dht.readHumidity();
    temp= dht.readTemperature();
    //Print temp and humidity values to serial monitor
    Serial.print("Humidity: ");
    Serial.print(hum);
    Serial.print(" %, Temp: ");
    Serial.print(temp);
    Serial.println(" Celsius");

    if (temp >= 25){
       digitalWrite(13, HIGH);  // turn relay on - which will turn fan on.
       Serial.println("Fan on because Greenhouse is too hot");
    }
    else {
       digitalWrite(13, LOW);  //turn relay off. 
       Serial.println("Fan is Off");
    }
    delay(10000); //Delay 10 seconds.
}

Arduino Code Example showing output in Serial Monitor

Smart Tank - Water Level sensor and Water Pump

  • A smart tanks is able to read 7 day rain weather forecasts from the Bureau of Meteorology and to use this information to adjust the amount of water stored in a rainwater tank.
  • If a large rain event is forecast, the smart tank will empty the rainwater tank.
  • Rain tank water is normally used to irrigate the garden.
  • The smart tank can also monitor for extreme heat days and also apply water to the garden to help plants transpire.

STEM Lab experiment and Control Logic

  • In this experiment we will enter our own Bureau of Meteorology rain data to control the operation of the smart tank.
  • Rain data will represent rain forecasts for the following day (24 hour forecast).
  • Rain water tank water levels will be constantly measured using ultrasonic distance sensor.
  • In this example the operation of the smart tank will be kept simple.
    • If rain event is 0mm - Pump will turn off.
    • If rain event is 1-20mm - Pump will turn on.
    • If rain event is 20-60mm - Pump will turn on.
  • Rain tank levels will be signalled using hand gestures (simulation of water levels in rainwater tank)

Parts list

Calibrate Max and Min values for Distance Sensor

  • Build the distance sensor circuit from Distance Sensor Project
  • Upload the code below and measure the maximum and minimum values for the distance sensor.
#define trigPin 10
#define echoPin 13

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  float duration, distance;
  digitalWrite(trigPin, LOW); 
  delayMicroseconds(2);
 
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) * 0.0344;
  
  if (distance >= 400 || distance <= 2){
    Serial.print("Distance = ");
    Serial.println("Out of range");
  }
  else {
    Serial.print("Distance = ");
    Serial.print(distance);
    Serial.println(" cm");
    delay(500);
  }
  delay(500);
}

Example distance sensor outputs during calibration

  • Use hand gestures to mimic rain water tank water level ranges.
  • In this data set the maximum value is 18cm and the minimum value is 4cm.

Send the Arduino Uno rain data using the Serial Monitor

  • The Serial Monitor can display data from the Arduino Uno and also send data to the Arduino Uno.
  • Data can be sent using the input bar at the top of the Serial Monitor.
  • Enter a value from 0 to 60 and then press Enter or click on the Send button to send the value to the Arduino Uno.
  • In this example we will send predicted rainfall data to the Arduino Uno.


Arduino Uno code to send rain forecast

/* Sending simulated rain forecast data to the Arduino Uno
*/

String rain_string;
int rain_integer;

// the setup function runs once when you press reset or power the board
void setup() {
  Serial.begin(9600);
  Serial.println("Enter the amount of predicted rain from 0 to 60mm");
}

// the loop function runs over and over again forever
void loop() {
  delay(500);
  if(Serial.available()){
        rain_string = Serial.readStringUntil('\n');
        rain_integer = rain_string.toInt();             // convert String to integer
         
        if(rain_integer == 0){
            Serial.println("No rain is forecast");
        }
        else if(rain_integer >=1 && rain_integer <= 20){
            Serial.print("Modest rain (mm) predicted ");
            Serial.println(rain_integer);
        }
        else if(rain_integer >20 && rain_integer <=60){
            Serial.print("Large rain (mm) event predicted: ");
            Serial.println(rain_integer);
        }
    }
}

Example output of rain forecast

Adding Relay Control for Water pump

  • A relay will control a peristaltic water pump.
  • The pump will be powered using a 5V power supply.
  • The relay will be controlled using Arduino Uno Pin 12

Fritzing - Circuit Diagram showing Distance sensor and Relay

Arduino Uno code

/* Sending simulated rain forecast data to the Arduino Uno
 * If tank is too full a peristaltic pump controlled using Pin 12 will empty the tank
 * Tank water level is measured using a distance sensor
 * Hand gestures will simulate tank levels
*/

#define trigPin 10
#define pump 12
#define echoPin 13

String rain_string;
int rain_integer = 0;

// the setup function runs once when you press reset or power the board
void setup() {
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(pump, OUTPUT);
  Serial.println("Enter the amount of predicted rain from 0 to 60mm");
}

// the loop function runs over and over again forever
void loop() {
  //  *** Measure water level using distance sensor ***
  float duration, distance;
  digitalWrite(trigPin, LOW); 
  delayMicroseconds(2);
 
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) * 0.0344;

    if (distance >= 400 || distance <= 2){
    Serial.print("Distance = ");
    Serial.println("Out of range");
  }
  else {
    Serial.print("Distance = ");
    Serial.print(distance);
    Serial.println(" cm");
    delay(500);
  }
  
  delay(1000);

  // *** Read rain forecast data using input from the Serial Monitor ***
  if(Serial.available()){
        rain_string = Serial.readStringUntil('\n');
        rain_integer = rain_string.toInt();             // convert String to integer
         
        if(rain_integer == 0){
            Serial.println("No rain is forecast.");
            Serial.println("Turning pump OFF");
            digitalWrite(pump, LOW);
            
        }
        else if(rain_integer >=1 && rain_integer <= 20){
            Serial.print("Modest rain (mm) predicted: ");
            Serial.println(rain_integer);
            Serial.println("Turning pump ON");
            digitalWrite(pump, HIGH);
        }
        else if(rain_integer >20 && rain_integer <=60){
            Serial.print("Large rain (mm) event predicted: ");
            Serial.println(rain_integer);
            Serial.println("Turning pump ON");
            digitalWrite(pump, HIGH);
        }
    }
}

Example output of Smart Tank code