Introduction: Arduino for Greenhouse, Garden or Growbox / Updated April 2016

About: I am a physician by trade. After a career in the pharmeceutical world I decided to take it a bit slower and do things I like. Other than my hobbies that involves grassroots medicine in S.E.&P Asia. I have buil…

Update March 2017
The RTC and DHT libraries are notorious for creating problems as there are so many of those libraries around carrying the same name. Therefore, In Step 17 I have linked to codebender where you can find the code with the proper libraries.
However, codebender is closing down, so I also added a zip file with the code and libraries, but I kept the libraries local, with the INO file, as not to overwrite your existing libraries.

I have been using Attiny chips for irrigation tasks in my garden, but having plans to build a greenhouse, an Arduino seemed to be the way to go as it has more ports. I know, there are many 'Garduino' type projects already, including ones that twitter the state of your plants, but I just wanted something more basic, so, what does an anal retentive Asperger do in such a case: build something myself.

No use of course to spend 23-25 euro's for an Arduino Uno and then still have to add a shield for peripherals: seemed a bit overdone and as I have built various 'arduino's' already, I decided to just get the chip, a crystal, and 2 capacitors + some more stuff and build the entire thing on an Archer experiment board that I bought 20 years ago but has been idle all that time (radioshack partno 276-168). The Archer experiment board has islands with 3 holes and 2 seperate tracks (Vcc and Gnd) snaking in between. Of course it can also be done on regular strip board, perfboard or one can make a PCB for it.

Note At the time I wrote this, it was economical to build an 'Arduino' yourself with a bare chip. However, as prices of Arduino clones have dropped considerably, it now in fact is much smarter to get an Arduino Pro Mini clone and add the required hardware to that

In the end I decided I needed to have the following functions

  1. measure temperature
  2. measure humidity of the air
  3. measure humidity of the soil
  4. measure water level in a container
  5. measure light, basically to determine if it is light or day
  6. measure CO2
  7. choose between measuring soil humidity or a pure hydroponics irrigation
  8. switch a fan
  9. switch a pump
  10. switch a heater
  11. switch a lamp
  12. log daily temperature


List of materials
Processor
Atmega 328 here to burn bootloader yourself or buy one preprogrammed
1x 28 pins IC foot narrow (or 2x 14 pins ic foot)
16MHz Crystal
2x 22 nF (often carries '223' imprint)
1x 10 k (brown-black-orange)
1x 100nF (often carries '104' imprint)
1x PCB
1x momentary make switch
perfboard This is what I used because I had that laying around idle for years already
NOTE:an attractive alternative is a cheap arduino clone such as the Pro mini or Pro Micro that can be had for a few dollars at e.g. Dealextreme.com or at AliExpress (currently 1.50 Euro)

Display
16x2LCD CG046-3007 A00, but any other will do.
1602 I2C module

PSU
1x 7805, isolated
1x 1N4001
2x 100uF (16 V en 25 Volt)
1x 1 k resistor (brown-black-red)
1x LED
1x psu connector
Note: Consider getting a plug in USB charger with a cord and forget about making your own PSU


Peripherals
1x LDR
1x DHT11 moisture sensor (e.g. from dealextreme)
1x make push button
1x throw switch
1x buzzer (I use the CMB-06, a triggerable buzzer) ($2.99) but use any other buzzer you have or are comfortable with e.g. this one. Aliexpress has some buzzers that literally cost dimes
1x NPN transistor (e.g.BC547)
1x 330 Ohm (orange-orange-brown)
2x 10k (Brown-black-red)

Solidstate relays
4x330 Ohm (orange-orange-brown)
4xLED
4x8pin dil foot
4x39MF22 SSR
4x2pin screw connector (mains voltage)
1x 5pin female printheader
1x 5pin male header 90degrees angle
ALTERNATIVELY: buy a ready made 4 channel mechanical relay for just about the same price as loose parts for the SSR, such as this one, or an even cheaper one.

bits and bolts
a couple of different colour wires, some print headers, four 3mm bolts and nuts, some 2.5 mm bolts and nuts, 4 spacers
solder tin, solder iron.
I have used Cinch plugs for connection... but actually these are hard to solder.

casing
I use two casings:
one for the processor and most of the peripherals (I use a plastic box that contained screws: 9x12x4.5 cm)
one for the SSR's (I used a Tic-Tac peppermint dispenser The bigger one for 100 mints: 8.5x2x5 cm)

Step 1: Arduino for Garden, Greenhouse or Growbox: Inputs and Outputs

Before I describe the construction I will discuss the individual items:

Processor
An Atmel 328 with an Arduino bootloader is used. That makes for easy adaptation and uploading of the program. It will be a "bare bones" setup with no USB entrance, but simply with the TTL Rx and Tx signals on a header. Consider using a cheap Arduino pro mini, pro micro or Arduino nano

PSU
Simply a 7805 circuit fed from a wallwart. No 3.3 Volts will be necessary Consider buying a ready to use cheap 5 Volt USB charger

Humidity and temperature sensor
A DHT11 sensor will provide that. It is a 3 pin sensor of which the data can easily be read by the Arduino. There is a library available.

Switch
Simply read as an input to set various functions in the software

Light
An LDR read by an analogue port. It basically is there to determine if it is day or night. This allows for extra light when the days are too short or to perform certain functions different at day or might(such as different day and night temperature, no irrigation at night etc)

Soil Moisture sensor
This sensor, read by an analogue port will give information about the humidity of the soil and signal the processor it is time to irrigate. There is an entire science on DIY soil moisture sensors. I will just be using the classic '2 nails' approach. The software and hardware will allow for the current through the sensor to be switched off, thus delaying corrosion.

Level sensor
This sensor checks if the water reservoir is still full. A simple float switch will suffice

Buzzer
used to give signals, e.g. if the water reservoir is empty. I use an old CMB-06 that has a trigger, meaning it can be triggered with a small current while it can get its main current directly from the power supply lines.

Solid state relays
I use 4 solid state relays to switch a fan, a pump, a heater and the lights. The solid state relays are separated from the processor print out of safety precautions. Consider using a cheap 5Volt 4 relay board


Step 2: Arduino for Garden, Greenhouse or Growbox: the Circuit

The circuit may seem a bit daunting at first, but it all makes sense. It is easy ro recognize the 'standard perfboard Arduino'

Step 3: Arduino for Greenhouse, Garden or Growbox: PSU

The PSU is a standard circuit build around a 7805. People that know their way around in electronics will probably have no problems with it. For the less experienced. I made a somewhat more extensive drawing.
With regard to the polarity of the LED: normally LED's have 2 legs: a short one and a long one. The short one is usually the cathode that connects to ground. The long leg is the anode that connects to the positive voltage.
With the 1k series resistor, the LED approximately receives 3.5 mA, whereas LED's can take some 15 mA. You'll see that most LED's are already pretty bright with a 1k series resistor.

Note: instead of a PSU with a 7805 stabilizer, consider buying a reliable 5 Volt USB charger or a 5 Volt PSU They are really cheap at various Chinese vendors (Dealextreme, Aliexpress)

Step 4: Arduino for Garden, Greenhouse or Growbox: Humiditity and Temperature

Fo rmeasuring of the humidity and temperature I used a cheap DHT11 module, It comes in various forms but though the bare module has 4 legs, it usually comes on a small PCB with only 3 pins, or 4 pins in which one is not connected. There are various libraries for the DHT11 to be used by the arduino. A good library however is the one from LadyAda.

Usually it is pretty well indicated what the supply lines and the signal lines are.
As some libraries presume the signal line is connected to arduino digital pin 2, that is what I have followed in this design

Note: after using it for a while, i found the DHT11 rather unreliable. The temperature can fluctuate 4 degrees between two subsequent reaadings and has a tendency to be too high. The DHT22 is a more accurate Sensor (so I am told),but it is more expensive.
i do not know how accurate the DHT11 is with regard to the humidity... but you could opt to keep the DHT11 but add a BMP180 for more accurate temperature. That gives you atmospheric pressure as well. It is an I2C sensor so it is easy to add.

Step 5: Arduino for Garden, Greenhouse or Growbox: Soil Humidity

Soil humidity is generally measured by reading the resistance between two pins in the soil. Generally, two types of sensors are used: two nails or pins stuck in the earth or 2 rods encased in gypsum, put in the soil.

Both methods have their pro's and cons. The (galvanized) nails may be put in the soil at various distances, influencing the resistance, however, they are simple and cheap and react quick to changes in the humidity. The gypsum method makes sure the rods have a fixed distance, but the reaction to changes in humidity are slower.

Both types are subject to corrosion in the soil, a process that is sped up by the electrolysis because of the current send through the sensor, however, the gypsum encased rods are less prone to corrosion because they are not directly exposed to the soil.

Though bare rods probably will have to be replaced every year because of corrosion, the gypsum sensor will also need to be replaced because of dissolving of the gypsum.

The corrosion of the rods can be delayed by limiting the electrolysis by only sending a current through the rods when measuring.

That is what I have chosen for in this design: The transistor used as a so called 'emitter follower'. Emitter followers function as voltage buffers. It is opened by a high level from a digital pin. The emitter is then pulled high (about 4.5 Volts). This voltage is then fed to the sensor (the two pins in the soil) and the voltage over the 10 k resistor is then read by an analogue pin. The transistor is basically any type of cheap NPN signal transistor such as a BC107 or a BC547. I used a VN147 a 30 year old 'universal NPN' transistor, for no other reason that I had that laying around and I kinda like the triangle shape it has.
It is possible to do this with a pnp transistor as well, with the emitter on the Vcc rail and the sourcing from the collector. However that would inverse the signal and you would need to switch the ON and OFF commands in the software.

The sensor and the resistor in fact form a regular voltage divider in which the voltage over R2 gives an indication of the resistance of the sensor and thus the humidity of the soil.

Resistance of the soil does not only vary with humidity but also with the type of soil. Generally, my soil in moist conditions renders a resistance of around 10 k between the sensor pins, but even if the pins would be shorted, the maximum current will be about 0.5 mA. It is therefore possible to leave out the resistor and feed the sensor directly from a digital pin (capable of delivering 40 mA), but I just feel happier having some protection of the arduino pins.

The 5V1 zenerdiode between the analogue pin and the earth is to protect the chip against high voltages that may build up if a long line to the probe is used. It is optional.

The software has a routine that will read the voltage over the 10k resistor 5 times and then calculate an average.

You will find some alternatives for measuring soil moisture towards the end of this instructable

Step 6: Arduino for Greenhouse, Garden or Growbox: LDR

I use an LDR to determine the light level. The LDR forms a voltage divider together with a 15 k resistor. When it gets dark, the resistance of the LDR goes up and thus the voltage over the 15 k resistor goes down. When it is light, the resistance of the LDR is low and therefore the voltage over the 15 k resistor is high.

LDR's generally have a vary wide range. The one I have is around 300 k in the dark and 300 ohm in daylight. As I only am interested in making a crude light, twilight, night reading, I determined the resistance of the LDR in what I called twilight. That was 15 k. Therefore, chosing a 15 k resistor in the voltage divider gives the broadest range.

I inserted the LDR in a clear casing (a pill bottle) and connected it via a thin wire to the arduino Vcc and analog pin 1 (that is pin 21 on an Atmega 328). The 15 k resistor is on the circuit board.

A good way to determine the value for the pull down resistor is the Axel Benz formula.
As we are only interested in a night and day difference, the pull up resistor is not that critical

Step 7: Arduino for Greenhouse, Growbox or Garden: the CO2 Sensor

Plants need CO2 like people need Oxygen.
If like me you are using a relatively small Growbox and you have some vigorous plants, CO2 levels can drop fast, which plants do not like. It is therefore good to guard the CO2 level.
The normal CO2 level in the atmospehre is about 340-395 parts per minute. A current atmospheric CO2 average can be found here. Plants can grow perfectly at that level, but if it drops to say 200ppm plants will have a grow reduction of about 50%.
Obviously it is possible to increase CO2 concentration. Plants really like a concentration of 1000-1300ppm.
Though there are a hoist of cheap gas sensors available for the arduino in the MQ series, they are not really practical for CO2 sensing. The only one in fact that can be used is the MQ-135 noxious gas sensor, but it needs calibration and is not easy to use.
CO2 sensors are commercially available but can be quite expensive. However I found a reasonably priced sensor for free in the Winsen MH-Z19 when I was scavenging an AC unit for parts. The MH-Z14, MH-Z16 and MH-Z18 are also useable. But I understand the MH-Z18 is quite expensive (92 euro's at aliexpress). The MH-Z16 and MH-Z19 are both about 25-30 euro.

The MH-Z19 has 3 ways of reading the CO2 concentration. It has a Tx/Rx UART, It has an analog output and it has a PWM input.
The latter is for my purposes the easiest to use.
The CO2 concentration = 2000 x (TH-2ms)/(TH+TL-4ms)

As the total cycle is always 1004 ms we only need to read TH and can simplify the formula to Cppm=2x(TH-2ms).

I am measuring CO2 once every hour. With regard to the action taken upon a low CO2 level. I have chosen to flash an LED, but you could opt to switch on a fan or open the valve of a CO2 tank.

Step 8: Arduino for Greenhouse, Garden or Growbox: the Level/float Switch

I have added a level switch to check if the water reservoir is still full. This is not only necessary for the well being of the plants but also for the well being of the pump as submersible water-pumps should not be left to run dry.

There are many ways in which one can construct a level switch: a magnet on a float that activates a reed switch, a tlt switch attached to a lever that goes up and down with the water level, 'feelers' in the water etc.

I have chosen a very simple approach. I have a rubber-duck floating in the water. That duck has a string attached that operates a micro switch that hangs over the top of the container. If the water goes down, so goes the ducky intil it pulls the switch. That switch is read by the Arduino that then switches off the pump and sends a signal to the buzzer.

The switch is connected to an ordinary digital I/O pin. perhaps it would be more elegant to attach it to an interrupt pin, but as the Arduino is not really held up in all sorts of routines, reading a regular I/O pin should not be much delayed.

In place of a rubber duck one can also take a piece of wood. Anything that floats, but is heavy enough to operate the switch. For the string I advise nylon fishing string

You will find an alternative for the float switch towards the end of this instructable

Step 9: Arduino for Garden, Greenhouse or Growbox: Buzzer

I added a buzzer for signalling functions (mainly to signal that the water reservoir would be empty). I have used the CMB-06 buzzer from Star. My main consideration was that I had that buzzer laying around for years already. It is a very handy buzzer though because it is triggerable. The advantage of that is that I do not need an arduino pin to deliver the entire current needed for the audio signal, just some current for the trigger. Therefore I do not have to add a transistor to drive the Buzzer.

The + and - are conveniently connected to the power supply and the 'C' (=control) pin is connected via a 1k resistor to an arduino pin (in fact pin 9, that has PWM)

The maximum average (!) current through the buzzer is stated as 23 mA, which could be delivered by an Arduino pin, but the data sheet requires a current source of about 70 mA for peaks. That is above what an arduino can safely deliver. Feeding it directly from the power line and only the trigger current being delivered from an arduino pin solves that problem.

Step 10: The Waterreservoir

I use an 86 liter cement bucket as a waterreservoir.
I have that dug into the soil to make sure it is lower than the plantbed. If it is higher than the plantbed, there is achance that yr pump, after it has been switched off, will start siphoning, emptying the entire bucket in your plantbed.
If for whatever reason your waterreservoir has to be higher than your plantbed, you need to install a vacuum release.

Step 11: Arduino for Greenhouse, Garden or Growbox: Solid State Relay

The 4 channel solid state relay is used to switch things like grow lights, a water pump a fan and a heater if necessary. It is almost a separate (albeit simple) project.
The circuit needs to be build 4 times and I have a print design available.
The circuit uses a 39MF22 solid state relay that simply needs a series resistor to limit the current. An LED shows whether the relay is active.
Because it is connected to 220 Volts, I have constructed it on a separate PCB and it is in a different case.
The 4 channels are controlled by digital pins 5,6,7 and 8 (Those are physicals pins 11-14 on the Atmega 328)
Inductive loads like the fan and the pump, may need a snubber network (100 Ohm resistor and 100nF capacitor in series over the connection). As these inductive loads are only low power I have left them out and have not experienced any problems.
This part is fully described in an other instructable.
.

Warning
This device connects to a mains voltage. That can kill you. If you are not acquainted with working with high voltage circuits then do not build this

Step 12: Arduino for Greenhouse, Garden or Growbox: the LCD

Considering there are only so much I/O pins on the Atmega 328, I decided to add an LCD through an I2C interface

The library to use is the new LCD-library from Malpertida

The pin-out of the i2C interface is such that it will nicely fit most LCD's.
It is possible to build your own I2C interface but i would advise against it. The one at Dealextreme is so cheap that building it yourself would be more expensive. Just the chip alone would probably already be more than the ca. 1.80 Euro, the entire ready built part costs at dealextreme.

I had considered to use Nokia 5110 display, but that needed some 4 or 5 data-pins. Surely I could use I2C either for that display or for the in and outputs, but by then I was already too far ahead to rewire everything for I2C for outputs and using I2C for the Nokia LCD is something I hadn’t figured out yet, but it is possible. The available library uses SPI -which is the fastest mode of communication- but as it is hard coded you would need to do some rewriting. therefore I opted for the regular LCD.
Using a 5110 display over I2C may seriously slow down the screen build up to maybe a second. You will find some initial reading here

Step 13: Arduino for Greenhouse, Garden or Growbox: Construction

It is hard to give a description of the construction as a 'this is how you do it' as the way i constructed it depended on the material I had on hand: a slightly opaque plastic box as a container and a piece of Archer PCB that after laying around for 10 years i finally wanted to put to some good use.

Therefore I can only give some general guidance.
I started with building the power supply followed by the Atmel 328 processor. The latter somewhat in the middle of the PCB so there would be space on both sides for various components.

It is a good idea to check the workings of every part after you finish it, That way you avoid building the entire circuit and have no clue why it isn’t working (if worse comes to worst). So after i was done with the power supply, I checked it for 5 Volts. Then after I built the processor, I inserted a 328 chip that i had preprogrammed with a test program, Added the interface for the relay/ssr and that worked . Wired up the FTDI tested it etc.

In the mean time I had prepared the the LCD by soldering the I2C piggyback to it and tested that on an Arduino UNO so I knew it worked. Then I put it in the box as well.

Initially I had thought to make the connection to the ssri/relay by running a cable through the box, but i decided I wanted a connector. As this needed to be a 5 prong connector and I already had made a female sil connector on the relay, i just opted for making a male sil connector on the box, using a lot of hot glue.

Don't make the mistake I made by mounting the DHT11 sensor on top of the casing.... especially if the LCD backlight is on, the temperature in and around the casing can rise, easily leading to a 2-5 degrees difference

Step 14: Arduino for Greenhouse, Garden or Growbox: the Software

The Software is what is tailored to my situation and you may well decide you need to make changes. I tried commenting as much as possible. I am sure the code could be simplified but this worked for me.

The most important elements are the following:
Libraries

Adafruit DHT library
Malpertida new LCD library
RTC library

Declarations

The usual: pins, constants, variables etc

Definition of characters for the LCD

Setup

Setting up the PinModes and their statuses
Setting up the LCD, upload the user defined characters
Print a welcome text
Flash the LCD twice
Give a quick buzz
set the RTC

Loop

First check if the water reservoir is empty or not. This is to avoid that the pump runs dry
If it is empty, give a buzz
Then read the level for dry vs wet as set by the variable resistor
Then set a voltage on the soil humidity sensor
and read he soil humidity


//--------------------------//
Read the DHT11 sensor
Read the LDR

//------------------------//
Display data depending on the status of the Pushbutton
//------------ACTIONS-----------//
if the temperature is below 20 degrees turn on heating
if the Humidity is over 60 % turn on the fan
If below the level set by the variable resistor-> start the pump
One could alter the code to only irrigate when it is light

Functions

sample

Will read a sensor 5 times and map the average to an 8 bit value

flash

can flash the LCD backlight a number of times. can be used as an alarm function

buzz

can sound the buzzer for a number of times

Step 15: Arduino for Greenhouse, Garden or Growbox: the Code in Codebender 1

The codebender code below measures the conductivity of the soil once every 4 minutes so the electrodes also only need a current to flow once every 4 minutes, thus sparing the electrodes.
If it finds that irrigation is necessary it will start the pump and it will keep measuring until the desired level of moisture is reached. It will then restart the 4 min period

Step 16: Arduino for Greenhouse, Garden or Growbox: the Code in Codebender 2

The codebender code below measures the conductivity of the soil once
every 4 minutes so the electrodes also only need a current to flow once every 4 minutes, thus sparing the electrodes. If it finds that irrigation is necessary it will start the pump and it will keep measuring until the desired level of moisture is reached. It will then restart the 4 min period.
However, if you flip the switch it will just do 6 short irrigations per day. It also measures CO2

Step 17: The Software in Codebender, Most Recent Code

This is the most recent code in codebender. It has all the functions of the previous code but some functions are added.

During Setup
If the Pushbutton is pressed and the Switchbutton is HIGH, the temperature scheme for tomatoes (lower temp at night) is toggled between OFF and ON.

If the Pushbutton is pressed and the Switchbutton is LOW the hourly temperature from the last 24 hrs will be printed on screen.

If the Pushbutton is NOT pressed there is a normal startup

During program Run
The Switchbutton switches between normal mode (pump action depending on soil moisture) and between hydroponics mode (6x irrigation per day)

If the Pushbutton is pushed in Normal mode: it shows the current date/time and the total time that the heating was switched on the day before, as well as the number of times the heating was switched on the day before.

If the Pushbutton is pushed in Hydroponics mode: it shows the current time/date and the total time the heating was switched on and the number of times it was switched on since midnight. It also shows the minimum temperature measured either since midnight, or since the device was switched on, whichever is shorter.

When connected to a serial monitor, there are some additional commands:
? prints temperature over the last 24 hours
l logs the current temparature
m prints the minimum temperature measured
T Switched the regime for tomatoes on
t Switched it off
W Switches to Wintertime
w Switched wintertime off (=DST on)
x prints to total time the heating was on over the past year

Step 18: Arduino for Greenhouse, Garden or Growbox: the Software: Special Characters

As I wanted a proper 'degree' character to use for Celsius (check yr LCD for character 123, perhaps that is suitable for you), I was in luck as the LCD allows for definition of 8 user characters. Decided to make an arrow as well as visual indication of an empty tank. With regard to the definition of characters for the LCD, that is simple to do with Malpartida's library On binary - hex converter, one can then find the hex equivalent of the binary number, but one can also directly send the binary number.

00100 -> 4

00100 -> 4

00100 -> 4

00100 -> 4

10101 -> 15

01110 -> E

00100 -> 4

00000 -> 0

Those binary numbers then can be send to the LCD with the help of the lcd.createChar function of the library. Of course one can also directly send the binary numbers

Step 19: Alternative Soil Resistance Measurement

Some tech stuff about soil humidity

When using a measurement like the one here, you are measuring resistance, or conductivity, depending on how you want to look upon it.
Conductivity is in fact not the best way to measure humidity of the soil as water itself is not really a good conductor, what you are actually measuring is the amount of dissolved ions in your plant-bed. A not so moist soil with lots of ions may give you a higher reading for conductivity than a wet soil with less ions.
Measuring your ions of course is a useful thing too as it gives information on whether your soil is depleted and if maybe it is time to add fertilizer.


Capacitive measureing
If you want a more reliable measurement of the humidity of your soil, then a capacitive measurement is more reliable: water influences the dielectric of a capacitor much more than ions do.
A capacitor in your soil sounds like having two metal plates in your soil in which the soil in between them is the dielectric. That is certainly possible, but it is also possible to have the plates of the capacitor next to each other instead of facing each other. That opens the way to etch them on a piece of PCB. Obviously the plates are isolated from the soil, otherwise you would just be measuring conductivity/resistance again. That has the added bonus that there will be no soil corrosion.

So once you have that set up, there are two ways of measuring: you could just measure the capacity of your diy soil capacitor, as the arduino is perfectly capable of doing that. The problem though is if you have a cable going from that sensor to your arduino, that is in fact a stray capacity that you are measuring as well. The way your cable is looped may influence your reading as well as someone approaching your cable. Using coax will help, but it still is best to do the measurement close to your diy capacitor.
Another way is to use that capacitor in a circuit whose output signal is depending on the value of your capacitor, such as a capacitor controlled oscillator. This can be done with a Schmitt trigger as is shown in the picture above.
The frequency of that oscillator is:
f=1.2/(RxC)

A changing amount of water in the soil will affect the dielectric of the capacitor and therefore the value of the capacitor and thus the frequency coming out of the oscillator. This frequency can be measured by the arduino with the frequency measuring library of the Arduino.
The value of the resistor depends on your situation. choose one that gives a good range of your frequency. The Arduino library supports frequncies to 8MHz.
If your capacitor is 10nF and your resistor 100kOhm, the frequency would be 1200 Hz. You will find a calculator here.
The FreqCounter.cpp file is hardcoded for digital pin 5 as input and uses both timer interrupts T1 and T2

Should you choose to use capacative measuring of the humidity, instead of using the various frequency counter libraries, you can also use 'PulseIn'. An example function of how to do that can be found below. I also made a full instructable on an I2C readable capacitive sensor.


Resistance measuring
Resistance measuring is one of the easiest methods. I previously already discussed just sticking two rods in the soil and measure the ADC value on the analogue port. However, when done with DC, the rods will deteriorate fast due to the electrolysis. One way to prevent that is to use AC current. The presented circuit with the '555' provides that or at least mimics it. The output signal is a frequency that depends on the resistance of the sensor.

The + power input can be as low as 3.5 volts and as high as 15 volts, so the 5 Volt of the Arduino is perfect. The CMOS LMC555 timer operates in its direct feedback mode, with a square wave output from pin 3 charging or discharging the 0.1 µf film capacitor through the fixed resistors in series/parallel with the conductive sensing probes.

The 2.2 uf non-polar capacitors in series with the probes assure that even the low level leakage currents from the CMOS chip do not flow through the probes. The capacitors, one being on each side of the probes, also assure that this circuit is galvanically isolated from other sensors that might be in the same aqueous environment.

R1 and R2 limit the range in case of a short circuit or extremely dry soil. R2 also has another function, as it discharges any slight DC build up over the capacitors in series with the probe that could make the oscillator stop.

The output frequency is transmitted from the open collector DIS output pin on the '555. This pin is in sync with the Output and will produce a square wave whose frequency/pulsewidth can be measured by the Arduino (e.g. through a timer interrupt or through 'PulseIn'). R3 is necessary since the DIS (discharge) pin of the 555 is an open collector.

As the current drawn by the 555 timer circuit varies linearly in proportion to the frequency of oscillation due to the charge and discharge cycles of the timing capacitor, the supply current can be used as an analog signal, to send to an analog to digital converter. Therefore a 1k resistor can be put in one of the supply lines (typically the Grnd) The current develops a voltage across the 1kohm resistor, to give a voltage signal if desired.

The picture above shows a function to measure the frequency (in fact the pulsewidth). The program below does the same.

I use value of 500 000 uS instead of 1 000 000 uS (= 1 second) for the division, because I want to get signal's period (T), not pulse length(tpulse). With duty cycle of 50%, T = 2*tpulse. However, unless you are interested in the true frequency, it doesn’t really matter for determining the soil moisture

int pin = 7;
unsigned long duration;

void setup()
{
  pinMode(pin, INPUT);
  Serial.begin(115200);
}

void loop()
{
  duration = pulseIn(pin, HIGH);
  Serial.print("Time ");
  Serial.print(duration);
  Serial.print(" usec ");
  Serial.print(500/duration);
  Serial.print(" kHz ");
  Serial.print(500000/duration);
  Serial.println(" Hz");
  delay(500);
}

Of course the above program is only a proof of concept/test program: we are not interested in specific frequencies but in differences in frequencies/periods. You need to determine for your soil what the right timing/frequency is for it to need water or not and incorporate that in your program the same way as previously you would have done so fr the voltage divider probe on an analogue port. It is still possible to use the potmeter on A1 to set a level, e.g. by mapping it to your frequency range, or with some If or Case statements.
To give an impression, when i tested it in my system (probes with about 6 cm distance, in so called 'Mel's Mix') a somewhat moist reading was 3kHz, while a wet soil gave 10kHz

Step 20: Arduino for Greenhouse, Garden or Growbox: an Alternative Level Switch

If you do not like a mechanical switch to signal the water-reservoir to be full, thee is a simple electronic solution:
Hang two electrodes at the level of the water that you want to signal at. They may come up higher but not lower. Instead of two loose electrodes one could also use a piece of PCB with two tracks etched on it.

Feed those two electrodes to the circuit as depicted here.
As long as the water is in contact with the electrodes, the transistor will receive a base current and open up. The collector will be pulled low and the arduino pin can detect that.
When the water-level falls below the electrodes, the transistor will not receive a base current anymore and close. The collector will therefore be high.

Mind you the Atmega 328 I/O pins have an internal pull up resistor and therefore a pull up transistor is not necessary in this circuit. To be sure though a 15k or 22k pull up resistor can be added between the collector and the +5 Volt line.

If you are short on I/O pins you could save a pin by using T1 not just to signal a low level to the processor, but also to directly steer the buzzer, or even to operate a Relay to switch off the pump, saving another I/O pin. But then again, most of the functions could probably be build with discrete components and the Atmega 328 has enough I/Opins for this project

Step 21: Arduino for Greenhouse, Garden or Growbox: an Alternative Float Switch

Determining whether the tank is empty is also possible with a reed switch as the figure shows: When the level drops to a specific amount, the magnet on the plunger will close the switch and that will be signalling the Arduino that the pump should not be operated any more.

The disadvantage of this circuit is that eventually the reed switch will magnetize and go to a permanent closed position.Replacing the relatively cheap reed switch of course will remedy that.

Step 22: Using Timers to Read Sensors

It is not necessary to continuously read the sensor(s). Especially if it is the soil humidity sensor, it is a good idea to only read that one at intervals, because that will limit the amount of DC flowing through the pins and thus slow down corrosion.
Rather than using delays, it is possible to use a timer interrupt.
In the example below the prescaler for timer 1 is set to overflow every second. The timer compare interrupt will count the seconds till 10 and then read the sensor. Read up on use of timers here.

// avr-libc library includes
#include <avr/io.h>
#include <avr/interrupt.h>
volatile int seconds=0;
void setup()
{
pinMode(LEDPIN, OUTPUT);
// initialize Timer1
cli();          // disable global interrupts
TCCR1A = 0;     // set entire TCCR1A register to 0
TCCR1B = 0;     // same for TCCR1B
// set compare match register to desired timer count:
OCR1A = 15624;
// turn on CTC mode:
TCCR1B |= (1 << WGM12);
// Set CS10 and CS12 bits for 1024 prescaler:
TCCR1B |= (1 << CS10);
TCCR1B |= (1 << CS12);
// enable timer compare interrupt:
TIMSK1 |= (1 << OCIE1A);
sei();          // enable global interrupts
}
ISR(TIMER1_COMPA_vect)
{
  seconds++;
if(seconds == 10)
{
seconds = 0;
readSensor;
}
}
void loop(){
  //other stuff
}

Keep in mind though that if you would set a timer such that your soilhumidity would be read say every 10 minutes, that if there is need to switch the pump on, you need to read the soil humidity constantly, otherwise your pump will flow for at least 10 minutes, before another reading is taken. That may be too much water.
The updated software now includes a 4 minute timer.

Step 23: Legal Issues

I sometimes get question asking if this can be used to grow "California Green". Sure, it can be used to grow virtually any kind of plant. But this device is no fool-proof way of doing that as each plant, be they tomatoes or hemp or bell peppers, need their own optimal temperature, irrigation, nutrients etc.

Although I have no problem with anybody growing or using cannabis, it is still a crime in many countries. As a result I cannot advise you in any way on how to do it, apart from the fact that I have no experience with growing cannabis.
Want to know about herbs, tomatoes, greens, whatever, I can help you, but if you want to use this to grow Cannabis, great, but I cannot advise you in it.

Step 24: Optimal Germination Temperatures

Seed Germination time in days at different temperatures
				
     									
degrees F 	32 	41 	50 	59 	68 	77 	86 	95 	104
degrees C	 0	 5	10	15	20	25	30	35	 40
parsnips 	172 	57 	27 	20 	14 	15 	32 		
onion 		136 	50 	13 	7 	5 	4 	4 	13 	
spinach 	62.6 	23 	12 	7 	6 	5 	6 		
lettuce 	49 	15 	7 	4 	3 	2 	3 		
cabbage 		51 	17 	10 	7 	6 	6 	9 	
carrots 		50 	17 	10 	7 	6 	6 	9 	
celery 		41 	16 	12 	7 				
peas 		36 	14 	9 	8 	6 	6 		
radishes 		29 	11 	6 	4 	4 	4 	3 	
asparagus 			52 	24 	14 	10 	11 	19 	28
tomatoes 			43 	14 	8 	6 	6 	9 	
parsley 			29 	17 	14 	13 	12 		
sweet corn 			22 	12 	7 	4 	4 	3 	
cauliflower 			19 	9 	6 	5 	5 		
beets 			14 	9 	6 	5 	6 		
turnips 			5 	3 	2 	1 	1 	1 	3
lima beans 				30 	17 	6 	7 		
okra 				27 	17 	12 	7 	6 	7
peppers 				25 	13 	8 	8 	9 	
snap beans 				16 	11 	8 	6 	6 	
cucumbers, 
summer and winter squash		13 	6 	4 	3 	5 	
eggplant 					13 	8 	5 		
watermelon 					12 	5 	4 	3 	
muskmellon 					8 	4 	3 		
As you might expect, the percentage of any seeds to germinate is maximum at the optimal temperature for that species.  As the temperature declines or advances from the optimal temperature, two things happen at the same time. While the percentage of seeds to germinate decreases, the number of days to germination increases.  That is the fundamental relationship between germination and temperature. See http://tomclothier.hort.net/page11.html