Introduction: Raspberry Pi Soil Moisture Sensor

Picture of Raspberry Pi Soil Moisture Sensor

Agriculture consumes between 80 - 90% of all freshwater in the United States. An easy way to conserve water in the agricultural sector is to install a soil moisture sensor. Soil moisture sensors measure the amount of water in the soil to maintain consistent and ideal soil conditions for plants. In some cases, installing a soil moisture sensor reduces residential irrigation by as much as 50%.

The following is a simple capacitive soil moisture sensor using a Raspberry Pi and a co-planar capacitor from the Zero Characters Left blog.

Excluding the Pi, the system can be built for less than $25.

Here's a tutorial on how to control an outdoor irrigation valve to automatically water your plants when the soil is dry.

Step 1: Materials

Picture of Materials

-- Raspberry Pi 2 Model B
This tutorial is based on a fully set-up Raspberry Pi, including GPIO libraries + GPIO cable w/ breadboard connector. I also recommend setting it up for wireless + SSH.

Other microcontrollers, like an Arduino, also work.

-- 1 MOhm Resistor (1/4 Watt)

This resistance was the best for my system, but a different resistor value might work better for your own setup. Experiment w/ different value resistors and see what happens!

-- Co-Planar Capacitor

Save the two EAGLE files (schematic and board file), then send to OSHPark. It costs ~ $10.00 for three.

-- 22 Gauge Wire (recommended to get stranded)

Recommended to get stranded wire b/c conducts better & is less likely to break.

-- GPIO Cable, GPIO cable adapter + breadboard

This is the bare minimum needed to build & test the system. If you want to install it outside after it has been tested and confirmed to work, coat everything in epoxy! ...Although a better way might be to replace the breadboard w/ a PCB Board . Molex 2-Pin Connectors are also a nice addition.

Step 2: Tools

Picture of Tools

-- Soldering Iron, solder, & Solder Sucker (or desoldering wick)
A soldering iron is (almost) essential for this project, especially for attaching wire leads to the co-planar capacitor. You can purchase a soldering iron, solder and solder wick (removes solder) for ~ $20-30, or find a local makerspace/hackerspace that will let you come in and use an on-site soldering iron.

-- Wire Strippers

-- Epoxy

-- Optional (but highly recommended): Multimeter (for testing and debugging!)

Step 3: Sensor & Circuit Design

Picture of Sensor & Circuit Design

An RC circuit provides a quick & simple way to measure changes in the sensor capacitance due to changes in soil water content.

Every RC circuit has an associated time constant, which is the time it takes the capacitor to reach ~ 63% of its maximum charge. The time constant equals the total circuit resistance times the circuit capacitance: τ = R * C

The time constant is used to measure changes in the sensor capacitance due to changes in soil water content. As the water content increases, the capacitance increases causing the associated circuit time constant to increase. The Raspberry Pi GPIO Pin 14 measures, or counts, the circuit time constant (how long it takes the capacitor to charge).

Step 4: Build It: Hardware Pt 1.

Picture of Build It: Hardware Pt 1.

Solder wire leads onto the co-planar capacitor (aka soil moisture sensor) pads. Test connection w/ multimeter. If the sensor is electrically connected, coat in epoxy & let dry before continuing.

If you're using stranded wire + a breadboard, you'll need to find a way to connect the stranded wire to the breadboard (b/c trying to shove it into the breadboard holes will make you want to pull your hair out). I stripped two breadboard wires and soldered them to the sensor leads. However, my connections were still a bit finicky and sensitive to touch and changes in light. Try different methods and see what works best. Use available materials and keep it simple!

Step 5: Build It: Hardware Step 2.

Picture of Build It: Hardware Step 2.
  • Connect the RPi GPIO pins to the breadboard. Connect the 3.3 V output pin to the "+" column along the side of the breadboard.
  • Connect the GPIO ground pin to the "-" column.
  • Connect one resistor end to the 3.3 V output (any of the holes in the "+" column). Connect the other end to any of the breadboard rows. Orientation of the resistor leads doesn't matter.
  • Connect GPIO pin 14 to the same breadboard row as the resistor. You can use a different GPIO pin, but remember to change it in the software program.The GPIO probe MUST go between the resistor and the co-planar capacitor.
  • Connect one of the co-planar capacitor leads to the same breadboard row as the resistor + probe. Connect the other lead to ground (any of the holes along the "-" column). It doesn't matter which lead goes where.

Step 6: Build It: Software

Write a code to measure the capacitance of the sensor! Use the fact that the time constant changes depending on the medium in which the sensor is installed (capacitance is much larger in water than in air).

Or you can just use mine :)

Keep in mind that this is a basic program and doesn't include a GUI. All commands are run on the Pi's terminal window (LXTerminal). The program prints the circuit time constant, correlated to soil water content, and a raw time stamp. If the reading is too low, the program also prints a reminder to water the plants. It stores the raw data in a text file. To end the program, use "Ctrl + Z" or "Ctrl + C". Modify and improve the program based on your own skills/needs.

Remember to change the watering threshold based on your own experimental discoveries!

Step 7: Testing!

Picture of Testing!
  • Test the software program and determine your ideal threshold.
    • Test the sensor in water and air first; this provides the upper and lower bounds on the sensor output. If you find that the sensor is not reading in either of these mediums, change the value of the resistor until you get a reasonable signal. Be sure to record the reading for at least 5 - 10 minutes. It is helpful to plot the results in a program like Excel or R.
    • Place the sensor in a cup of dry soil. Add a small amount of water and measure changes in sensor output over time (wait at least 5 - 10 minutes). Repeat this multiple times to get a better understanding of the reading and to improve the software/hardware as necessary.
    • If you are not getting a reading in either medium, try checking the electrical connections on the sensor.
  • Fix the program as necessary.
    • Your signal will likely be different than mine due to minor differences in your sensor and general setup. Use your findings from above to find an approximate value at which your soil is too dry.

Step 8: Enjoy!

Picture of Enjoy!

Install in a sunny spot and use it to maintain consistent watering of your beloved plants!

Note: In the system pictured above, the Raspberry Pi is also controlling a solenoid irrigation valve, so the entire watering system is automated! This is fairly easy to do and if there is sufficient interest I will include an overview of this process as well.

Happy hacking!

Comments

bfelmokh made it! (author)2016-04-22

It work Fine also with this type of Soil Sensor Great :D

if there is no water it write value in file and the sensor led blink
else nothing showing and the led is on

xxlukas (author)bfelmokh2017-05-03

I have pretty bad experience with this resistive sensor-even if you limit the measurement time to ms due to electric contact with the soil it suffers corrosion of electrodes and soil electrolysis which affect measurement and destroy sensor eventually. But I found cheap and usable Chirp! sensor ($ 6) which is hackable via I2C - see my project here: https://youtu.be/WLyolOGSAXI

jenfoxbot (author)xxlukas2017-05-08

Well that's interesting, def want to avoid corrosion if it's actually going to be used to maintain plant life. Thanks for the feedback + alternative recommendation!

xxlukas (author)jenfoxbot2017-05-09

Hi Jen, one of the guys from YT recommended me also Xiaomi Flora sensor-it is more expensive but it provides also temperature, sunlight intensity and soil fertility (...actually I don't know how the measurement is done for this one-maybe there is a correlation between soil fertility and soil electric conductivity?).
See here how to hack it https://wiki.hackerspace.pl/projects:xiaomi-flora (I have not tried it yet)

jenfoxbot (author)xxlukas2017-05-15

Awesome, thanks for the recommendation, will check out the sensor you linked to!

DanD186 (author)bfelmokh2017-04-12

i have this kind of sensor too. How can I connect to the Rpi?the pins rather, IDK the analog input of the Pi, and the code you used, i badly needed this for my project :D

thx

jenfoxbot (author)bfelmokh2016-05-20

whoops, missed this somehow. thanks for the response, diy_bloke!

diy_bloke (author)bfelmokh2016-05-20

Your sensor is not really appropriate for this project.
If you use the entire module, the connections will be all wrong and if you only use the sensor part then you are connecting a resistive sensor instead of a capacitive and your readings will all be wrong

dyoung48 (author)2016-11-01

Why is the resistor important to this build?

jenfoxbot (author)dyoung482016-11-02

Good question! The simple resistor-capacitor ("RC") circuit is used to measure changes in the capacitance of the soil moisture sensor. The RPi logs the time constant of the circuit (aka how long it takes to charge the capacitor) which changes depending on moisture and the resistor needs to be large enough to be able to see those small changes. Hope that helps!

dyoung48 (author)jenfoxbot2016-11-02

Is that reliant to this particular soil moisture sensor?

I'm curious because I have a soil moisture sensor that puts out voltage. Up to 2.8V and each of those voltages is directly porpotionate to how wet the soil is.

jenfoxbot (author)dyoung482016-11-02

Yes, this particular soil moisture sensor is a co-planar capacitor. If your soil moisture sensor is putting out voltage, it is not just the sensor but includes additional circuit components. If you're having trouble calibrating it or whatnot, I'd suggest doing a search in Google for the specific sensor you are using and then reading up on it.

You could also do what I did to try and calibrate my sensor -- bake some soil in the oven to get all the moisture out, then all small volumes of water and make readings over time. Takes a loooong time but it's not terribly difficult.

mraquino (author)2016-03-24

Hi Jen,

I know it's been a long time since you wrote this article but, I tried to reproduce it and got something weird. I always get the same message.. my plants need water, event when I got a bottle with water over the soil. I followed your instructions step by step, line by line. I am also using your code.

Any thoughts?

jenfoxbot (author)mraquino2016-03-24

Hello! Based on your description, sounds like something is wrong with the sensor signal. Are you getting a sensor reading output? Does it change at all? Try checking your connections -- a multimeter can be super helpful with this if you have one on-hand.
If it's not the connections, output the sensor signal and see if it is changing at all. If it's not changing, it could be that the circuit is not sensitive enough (aka you'll need a larger resistance). LMK if these suggestions prove useful!

mraquino (author)jenfoxbot2016-04-07

The same values with with both air, dry soil and wet soil..

jenfoxbot (author)mraquino2016-04-07

Huh, that's odd. Did you coat the sensor in anything? Seems like it's not making direct contact with the dielectric.

mraquino (author)jenfoxbot2016-04-03

Hey!!! Thanks for the response. Well I made a lot of measurements, resoldered a few times the sensor but still stuck into this hheh.

I made a few tests with different resistances.. and believe me.. the soil I am using has a lot of water

So the responses I got here were:

For 10M Resistor

1459726298.7 0.122217178345

1459726299.82 0.118407011032

1459726300.95 0.121515989304

1459726302.07 0.128042221069

1459726303.2 0.139445066452

1459726304.35 0.143229007721

When using 20M resistor

1459726352.18 0.16845202446

1459726353.35 0.174252033234

1459726354.53 0.177757978439

1459726355.71 0.171924114227

1459726356.88 0.17144203186

30 M

1459726387.79 0.214463949203

1459726389.01 0.213176965714

1459726390.23 0.21272110939

1459726391.45 0.219429016113

40 M

1459726421.87 0.233628988266

1459726423.11 0.231085062027

1459726424.34 0.246037006378

1459726425.59 0.234977006912

1459726426.83 0.23019695282

1459726428.07 0.237556934357

and finally 50 M

1459726442.36 0.272974967957

1459726443.63 0.280236005783

1459726444.92 0.282718896866

1459726446.2 0.277140855789

1459726447.48 0.281071186066

1459726448.77 0.279512166977

Well it seems there´s something related to either the my sensor or my RPI... not sure if the second option is possible... the weirdest thing is that I got good measurements using something like this https://www.arduino.cc/en/Tutorial/CapacitanceMeter and an Arduino Mega..

jenfoxbot (author)mraquino2016-04-07

So the first thing that I notice is that the sensor reading increases with increasing resistance -- which means that the sensor is outputting some kind of signal. Are you getting different sensor readings in dry soil vs. wet soil with any of those resistance values?

jweiser (author)2016-02-08

Hey there, first of all thanks a lot for the Pro tip with the capacitor, I was about to buy a sensor for 60 bucks and this one saved my wallet! (and made me a bit smarter with electronics : >)

I've built it and it works like a dream, I am even able to control a little pump to water my plants. I have also noticed an increase and a decrease in the readings and wanted to share my thoughts with you guys, see what you think. I'm using the model b.

I also built a light module that, like the pump, is controlled over a 2 channel relay board. My program runs those as seperate instances in different threads. Since my plant is 2 weeks old, the roots aren't really developed enough to get the water so the soil is pretty stable. the readings are ok, I am doing 100 readings and taking the average of those, but from time to time it jumps about 10 counts.

I think, the change is due to the cpu timing that each thread occupies the cpu. If the light is on, there are more instructions to be processed which takes longer time, therefore I get less counts. Lights off means more counts because my water pump thread has more time or rather gets faster back onto the cpu. would that make sense? therefore you could increase the precision of the sensor if you could influence the cpu time but I wouldn't know how to do that in python... anyways I would appreciate your feedback!

jenfoxbot (author)jweiser2016-03-24

Whoops, apologies for missing this! Based on your description, it sounds like you are the right track re: cpu timing. Yes, I would assume that if you add more stuff for the computer to do, it could affect the sensor reading.

The way to get around this is to use a separate function for the other stuff you want to have happen, then call that separately in a main function. Hopefully this helps if you haven't already figured it out!

diy_bloke (author)2016-01-12

Very interesting.
I do capacitive mositure metering as well, using just two virgin PCB pieces in plastic in the soil. Use that as the 'C' of an RC oscillator and measure the output with 'PulseIn' on an Arduino. Readings are pretty stable. Initially I just use the Arduino as capacitance meter but I found the RC oscillator to work more reliable

jenfoxbot (author)diy_bloke2016-01-15

Thanks! Love your approach as well, very clever/creative!

tchester (author)2015-10-08

I'm having the same problem as theblindspring posted a few months ago...Avg discharge is nearly identical in air as it is in glass full of water. I've tried 1/4 watt 1MOhm resistor, 1/4 watt 10MOhm, and even 1/2 watt 1MOhm. I can get time from 1.004 to like 1.3 but I still get similar timing as the other resistors. I noticed the max voltage is .4, doesn't get any where near the 63% threshold for an RC circuit. Any ideas what could cause this?

jenfoxbot (author)tchester2015-10-11

Hmm, could be the result of a variety of issues.. Is the GPIO input before the sensor?

If you have access to a multimeter, were you able to measure a difference in the sensor capacitance in water vs. air?

Re: Max voltage of 0.4 V, that is surprisingly low. What voltage difference is this and under what conditions did you measure it?

tchester (author)jenfoxbot2015-10-12

Alright, so changing to a 1MOhm resistor I am getting 2.16V. And yes, the GPIO input is before the sensor.

I do have a multimeter but it does not have a capacitance setting.

So applying 3.3V to the system the max voltage across the capacitor was 0.4V. Now the maximum voltage is 2.16V

jenfoxbot (author)tchester2015-10-13

That's great! I glanced over that you'd used a 1/2 W, 1 MOhm resistor. RPi GPIO probably doesn't have enough power output for that one.

Are your sensor measurement values now different in air vs. water?

tchester (author)jenfoxbot2015-10-14

Not when using time like you do. I found the OP code you borrowed from here: https://learn.adafruit.com/basic-resistor-sensor-r... or here: http://www.raspberrypi-spy.co.uk/2012/08/reading-a...

When I use counts I get distinct differences. In air I get a value of 0-4. In water I get values ranging from 600-1000. These counts are faster than millis even!

The real problem is the accuracy. I can get 30 readings in a row and they vary by +/-15%. When averaged it drops to about +/-5% accuracy. In flooded soil I get readings of 1000, but then once I stop the flow of water it drops down to about 300. So I've been using that as my 100% soil saturation value, the soil tends to hover around 140-160 within 12 hours of watering but since it is fall it's hard to tell the reading in dry soil since my garden is shaded :(

To make the readings even more accurate I am using a 6 hour moving average. I take 30 readings every hour and average those. Then I take the moving average over 6 hours to plot my data.

I don't want to just put dry soil in a cup because I'm not sure how much that will affect the reading versus having a volume of larger soil. Also the compaction of soil differs. So I won't be sure of the depletion value until next spring.

Finally I need to point out some flaws in your code:

"while (reading <10.00):" This entire code block simply counts to 50 when a count is less than 10. You are not actually getting any more than 1 reading each time you run this if the first reading is less than 10.

IMO instead of "while True:" is should be "while (reading <10.00):" and you'll need to define "reading = 0" initially

But then you need to change the start time to before the while loop and you will also need to move the end_time outside the loop after the break as well as the logic to say you need to water.

Thanks for taking the time to respond to my inquiries, I think things are getting quite polished now in my system.

jenfoxbot (author)tchester2015-10-14

Glad to hear that you got it working! Happy to provide help where I can.

Re: Code, yea, I'm sure there are plenty of ways I could update/improve the code. When I first started building the system, I wanted to have the sensor data upload to a web server where I could monitor and control the whole system. Unfortunately, as a freelancer, I can only spend so much time and money on my personal projects. In the end, instead of trying to perfect it, I decided it was better to make the whole thing open source and let folks modify and improve it where they see fit, which is precisely what you have done!

Maybe one of these days I'll go back and update the code, but for now I'm happy to see that others are building off of the basic module :)

VincenzV (author)2015-09-22

Thanks for the great Tutorial! Does anybody know where I could order the PCB in Europe or even better in Germany?

Nielsd (author)VincenzV2015-09-26

They do ship to europe (The Netherlands, at least).

VincenzV (author)Nielsd2015-09-26

Thank you! Sounds good! I Hope it won't take to long haha. Do you already have experience?

jenfoxbot (author)VincenzV2015-09-22

Thank you! I think OSHPark ships to Europe (?), but for a cheaper option try visiting the makerspaces in Germany. There are quite a few in Berlin, like the Fab Lab. You might be able to manufacture the PCBs there, or someone would probably be able to give you the name of a company that could make them for you.

VincenzV (author)jenfoxbot2015-09-23

Thank you for that Fab LaB hint! Unfortunatly there is nothing like that around me. All the companies I've found in the Internet are very expensive. So lets hope somebody knows a better one.

Just another question, do you or anybody else has experience with long cable (about 20 meters (~22 yards))?

jenfoxbot (author)VincenzV2015-09-23

Ah, yes PCB manufacturers can be expensive. Best of luck finding a source!

Which wires are you looking to make 20 m?

One of the systems I built recently involved system wiring over 8 meters (motion triggered sound system). In general, I try to keep internal system wires fairly short to maintain signal strength, esp. between sensing circuits like the RPi and the soil moisture sensor. You may need a signal amplifier for super long wires between the sensing circuit and computer. If you just want to run an extension cord to the whole system that should be just fine.

VincenzV (author)jenfoxbot2015-09-24

These do-it-yourself PCB etching boards sound very interesting, thank you! But let's see, I still hope to find a good manufacturer, cause my crafts skills are not the best haha :D.

I think I take a wire with a diameter of 1.5 mm to keep the resistance low. I hope it works without amplifier, but we will see :)

Thank you for fast and good support! Something I've rarely seen in the internet! :)

jenfoxbot (author)VincenzV2015-09-25

Of course, happy to help! Best of luck finding a good source for PCBs + building your system!

jenfoxbot (author)VincenzV2015-09-23

Also, I just realized, if you can't find a PCB manufacturer, you could always just make your own sensors. Electronic supply stores usually carry do-it-yourself PCB etching boards. Since coplanar capacitors are fairly simple PCBs, this should be doable.. just remember to coat the copper plates in a thin layer of insulating material (e.g. spray paint or nail polish) :)

fduraibi (author)2015-09-21

Hey all. To people who have done this, How stable is your capacitive sensor? I built 3, covered one with Solder GreenMask, one with PlastiDip and the third left it naked as an air reference while testing. And also have a resistive sensor as a base reference. The resistive works great and numbers are stable over time, however, the capacitive ones give increasing result over time!
E.g. I dip them in water and they read 500, the next day they reach e.g. 700+ while still in the same water level! tried with soil and it still increases in a fast rate where it should be stable or decrease slowly as moisture in soil decreases. (PlastiDip was giving better and more stable result in the first 3~4 days of testing, but it failed on the fifth day which made me believe it is not very water proof)

jenfoxbot (author)fduraibi2015-09-21

Glad to hear that you were able to build some test prototypes. Your problem sounds very similar to the first sensor circuit that I designed: I used an additional capacitor in that first design and it caused my sensor reading to continually increase over time regardless of medium.

Are you only using the 1 MOhm resistor and the capacitive sensor in series as the measurement circuit? If the resistive sensor is connected to the capacitive sensor it may skew your measurement.

Also, just to clarify, did you coat the whole capacitive sensor or just the electrical connections? The PCB pads need to be in direct contact w/ the medium, so you'll only want to cover the solder joints.

fduraibi (author)jenfoxbot2015-09-21

Yeah I am not using any capacitors, and using 1 MOhm in series to charge the sensor. Also my resistive sensor is isolated and has its own circuit and I don't read from them at the same time.

For the coating, I think you are confusing the resistive with the capacitive. For capacitive sensor to work we need to cover the whole thing with water resistance material to insulate it, otherwise the water in the soil will conduct and pass current between the PCB pads and it will turn into a resistive sensor instead. For capacitive the isolation insures that both sides (+) and (-) will stay isolated so there will be no current flow.

jenfoxbot (author)fduraibi2015-09-22

This design relies on the changing dielectric constant of the medium surrounding the capacitive sensor. The dielectric constant of water is about 80, air is ~ 1.0001, and soil is typically between 2 - 5. If you coat the sensor, you will not get a reading that depends on the dielectric constant of the surrounding medium but will instead get a reading of the insulating material. Try the same setup w/out the coating and see if your measurements are more consistent.

fduraibi (author)jenfoxbot2015-09-22

I am not trying to be rude but I suggest that you go back to the blog post from [Zero Characters Left] and read it again. "create a sensor that consists of isolated conductive plates, separated by a narrow gap. The assembly must be waterproof". And later he wrote "To make sure the isolation (soldermask) on the sensor is really waterproof, I'm performing an extended soak test."

jenfoxbot (author)fduraibi2015-09-22

I definitely appreciate you pointing this out since it is an important aspect to consider. Plus, gotta be sure that the design is accurate!

Re: Zero Characters Left blog, what I got from his explanation is that
the PCB board does consist of isolated plates + the soak test showed that the board was waterproof (the remainder of the paragraph you refereced states: "As luck would have it, there is an inexpensive technology that enables
us to build isolated conductors in arbitrary shapes
with ridiculously small tolerances. This technology is printed circuit
board fabrication.").

You can specify a soldermask
w/in the Eagle board files (boardname.GTS + boardname.GBS). In my experience w/ the PCB board, the coating will eventually get chipped off from repeated abrasion w/ soil and rocks as you remove and insert it into the soil (and then it might short). Might not hurt to add in a thin layer of insulating coating to prevent or to fix this. Hope this helps + thanks for the input!

fduraibi (author)jenfoxbot2015-09-22

Without isolating the plates the current will flow between the cathode and anode so it won't hold a charge. And that is how the resistive sensor work where the resistivity decreases as the moisture increases.

maeximie (author)2015-07-14

Hello, my python skills are really still on beginners stage. When I run your code I get always the same error message and the sensorData.txt is empty. I couldn't figure out what's the problem. I hope you can help me. Here is the error message:

pi@raspberrypi ~/SoilSensorAPI $ sudo python JenFoxBotSMSV1c.py

^CTraceback (most recent call last):

File "JenFoxBotSMSV1c.py", line 27, in <module>

reading = RC_Analog(4) #store counts in a variable

File "JenFoxBotSMSV1c.py", line 18, in RC_Analog

counter=counter+1

KeyboardInterrupt

jenfoxbot (author)maeximie 2015-07-14

My first guess would be that the file path is wrong.. Could you copy and paste the code that you're using?

maeximie (author)jenfoxbot2015-07-14

here is the code original code from your guthub. I didn't change anything. The Indentions got lost by copying the code. the file is lacated in teh rasps home folder: pi@raspberrypi ~/SoilSensorAPI. If I delete the "SensorData.txt" the file is crated again while the next run of the code. But there are no data logs

inside.

import RPi.GPIO as GPIO

import time

GPIO.setmode(GPIO.BCM)

file = open("SensorData.txt", "w") #stores data file in same directory as this program file

#Define function to measure charge time

def RC_Analog(Pin):

counter=0

start_time = time.time()

#Discharge capacitor

GPIO.setup(14, GPIO.OUT)

GPIO.output(14, GPIO.LOW)

time.sleep(0.1) #in seconds, suspends execution.

GPIO.setup(14, GPIO.IN)

#Count loops until voltage across capacitor reads high on GPIO

while (GPIO.input(14)==GPIO.LOW):

counter=counter+1

end_time = time.time()

return end_time - start_time

#Main program loop

while True:

time.sleep(1)

ts = time.time()

reading = RC_Analog(4) #store counts in a variable

counter = 0

time_start = 0

time_end = 0

print ts, reading #print counts using GPIO4 and time

file.write(str(ts) + " " + str(reading) + "\n") #write data to file

while (reading < 10.00):

time_start = time.time()

counter = counter + 1

if counter >= 50:

break

time_end = time.time()

if (counter >= 25 and (time_end - time_start) <= 60): # if you get 25 measurements that indicate dry soil in less than one minute, need to water

print('Not enough water for your plants to survive! Please water now.') #comment this out for testing

# else:

# print('Your plants are safe and healthy, yay!')

GPIO.cleanup()

file.close()

theblindspring (author)2015-06-08

Okay, I lied I have some more questions. In you code, you have this loop:

while (reading < 10.00): time_start = time.time() counter = counter + 1 if counter >= 50: break

Provided 'reading' is less than 10, wont 'counter' always be 50 since we never change the value of reading?

jenfoxbot (author)theblindspring2015-06-15

Hmm the intention of that loop was to count how long the sensor reading was under 10.0, so my initial reaction would be to say that the loop adds one to counter each time the sensor reading is under 10, unless it equals 50 and then it skips it.

Now that I'm looking at it more closely, it seems that an if statement would be better than a while statement. In other words, you may be correct in that analysis, I'll have to go back and switch a couple of things to figure it out for sure. Thanks for catching that.

theblindspring (author)jenfoxbot2015-06-16

I was able to figure things out I think. You mentioned that people might get different readings, I just wasn't sure how different. It looked like your graph had signals every 1 second. I tested both in air and in water, and the signals are consistently different, but barely.

Avg Time in air: 0.1003 seconds

Avg Time in water: 0.1006 seconds

Any idea why the readings would be so drastically different?

About This Instructable

104,711views

320favorites

License:

Bio: Dabbled in dark matter, settled into engineering with a blend of inventing and teaching, always trying to solve problems + learn new things!
More by jenfoxbot:Build an (Easy) Floor Piano!Micro:Bit Puppet "Text Messaging"!Anti-Facial Recognition Wearable No. 1
Add instructable to: