When I finished building my weather station it was on a large full size breadboard. I didn’t like that it there was so much space on there that was just wasted and I had a half size sitting around that I thought would work well. Unfortunately, the ADC wouldn’t let everything else fit properly. I did some research and found that Microchip also produced a 2 channel ADC called the MCP3002. Since I was using only 2 channels on the MCP3008, I thought this would work nicely and I counted all the slots on the half size breadboard and it would fit perfectly! So I ordered a couple from Newark…

When they came in I had to test to make sure it was going to work, so I placed in the half size breadboard, wired up a TMP36 analog temp sensor, and connected the breadboard to my spare Pi. Well, come to find out, the driver I had didn’t work. Neither did the other one I found online nor the others I found. I was a bit depressed because I really wanted it to work.

My last hope laid on the Adafruit forums. (Love Adafruit by the way!) I was a bit worried as they don’t sell the MCP3002 and they have messages on there about only supporting their products. So, reluctantly I posted a question on the forum asking if the driver they provide for the MCP3008 would work for the MCP3002. At first their people informed me that it would work, but I told them I had tested it and it didn’t. In one of my responses I made sure that I mentioned that I had wired it as per the datasheet and added a link.

Come to find out, the reason their driver wouldn’t work is because the 3002 only wanted 4 bits sent to it for the request and the 3008 wanted 5. So, Rick (who I think works for Adafruit) helped with adapting that part of the driver. When I added his piece to the 3008 driver, it still didn’t work. I then took another look at the datasheet and found another difference in the 3008 vs the 3002. The 3002 only provided a 11 bit response vs the 12 that the 3008 provided. I then updated the code to account for that and voila! it worked like a charm.

After I got it working, I posted about having to make the other change. Rick then asked me to post the full driver so that it could be added to their python library. So yeah, that’s the story of writing my first driver…

Here it is by the way if you need it:

def readadc(adcnum, clockpin, mosipin, misopin, cspin):
if ((adcnum > 1) or (adcnum < 0)): return -1 GPIO.output(cspin, True) GPIO.output(clockpin, False) # start clock low GPIO.output(cspin, False) # bring CS low commandout = adcnum << 1; commandout |= 0x0D # start bit + single-ended bit + MSBF bit commandout <<= 4 # we only need to send 4 bits here for i in range(4): if (commandout & 0x80): GPIO.output(mosipin, True) else: GPIO.output(mosipin, False) commandout <<= 1 GPIO.output(clockpin, True) GPIO.output(clockpin, False) adcout = 0 # read in one null bit and 10 ADC bits for i in range(11): GPIO.output(clockpin, True) GPIO.output(clockpin, False) adcout <<= 1 if (GPIO.input(misopin)): adcout |= 0x1 GPIO.output(cspin, True) adcout /= 2 # first bit is 'null' so drop it return adcout # change these as desired - they're the pins connected from the # SPI port on the ADC to the Cobbler. There are 2 Chip Select pins. # one for each ADC SPICLK = 18 SPIMISO = 23 SPIMOSI = 24 SPICS = 25 # set up the SPI interface pins GPIO.setup(SPIMOSI, GPIO.OUT) GPIO.setup(SPIMISO, GPIO.IN) GPIO.setup(SPICLK, GPIO.OUT) GPIO.setup(SPICS, GPIO.OUT) Read the rest of this entry

Rain Gauge

The rain gauge to me was one of the easiest to do, mostly because I kind of cheated a bit. Since I didn’t think I could create a sensor for cheaper than I could buy one, I spent $20 and bought the Acu-Rite gauge at Wal-Mart and modified it to my needs.


To start off, you’ll need to take apart the “gauge” piece and set the wireless display aside. This is fairly easy, as the main cover and tipping part comes off fairly easy. Next, you’ll need to remove the screws under the battery compartment to remove the circuit board. There are two wires coming out of the circuit board that go to the reed switch within the gauge that need to be clipped.


The reed switch is set within the tipping part, so carefully pull it out and strip the wires. You’ll need to attach wires to each of these. I use some telephone cable/cat3. I usually start with attaching about 10 feet of wire just in case. When attaching, make sure you solder the wires and use shrink tube to protect the connection.


Next, carefully slide the reed switch back into the tipping piece. Real quick explanation of how this works….A reed switch “closes” when a magnetic field is near. So we run current through the reed switch and place a magnet in the tipping mechanism to pass over the reed switch when it tips. When rain fills up a side of the gauge it tips over and the magnet causes the reed switch to complete the circuit for a brief period, which we can count….


We then need to drill a hole in the battery compartment and in the bottom piece to allow the wire to go through. Make sure to put a little hot glue in the hole in the bottom to protect against the elements a bit.

For testing, plug the two wires into a breadboard, one needs to run to power and the other to one of the pins on the Raspberry Pi (I believe I use number 17). In order to count how many times the gauge tips, we have to use GPIO interrupts. Before I forget, each tip is .02 inches of rain….

To keep count, I use a script that runs when the Pi starts up and monitors that pin. When the gauge tips and it detects a voltage “spike” it opens a file, takes the number, adds 1 to it and then rewrites the file with that number. (When I run the script that gets the current weather, I access this file and multiply by .02) At midnight every night, I also run a script that resets the number in the file to 0.

Here is the file I use to monitor the pin…

#!/usr/bin/env python2.7

import time
import os
import RPi.GPIO as GPIO

First bit is to set up the normal stuff…I have to give some credit to Alex Eames @ http://RasPi.tv/ for the pieces of interrupt code. http://raspi.tv/2013/how-to-use-interrupts-with-python-on-the-raspberry-pi-and-rpi-gpio

# GPIO 17 set up as input. It is pulled up to stop false signals
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

Next we need to set up the pin for interrupts. We’re setting up pin 17 as an input and using an internal resistor to pull it down to 0 when there is no current.

def my_callback(channel):
tfile = open("/home/pi/rain_count.txt")
text = tfile.readline()

rain_count = int(text)
rain_count += 1
tfile = open("/home/pi/rain_count.txt", "w")


Now we create the function that gets called when a “spike” is detected. This function opens the file called “rain_count.txt” and reads the number, adds one and then writes the new number to the file. When doing this, don’t forget to create the rain_count.txt file prior to running this and place a 0 in it.

GPIO.add_event_detect(17, GPIO.RISING, callback=my_callback, bouncetime=300)

Now we add the interrupt event that monitors pin 17 and says that we want to monitor it for a rising event (I call a spike). When it is detected it calls the function “my_callback” and then waits 300 milliseconds before it will try to detect another one. (The bounce time is necessary to keep from getting false positives.)

while True:

The last bit is just an infinite loop to keep the script running. To run this at startup of the Pi, you’ll need to add a line to the crontab file:

@reboot python /home/pi/rain-gauge.py &

The clearing file is fairly easy too….
#!/usr/bin/env python2.7
import time
import os

tfile = open("/home/pi/rain_count.txt", "w")
rain_count = 0

And add this to your crontab file to run at midnight…
* 0 * * * /home/pi/rain-clear.py

The last bit is grabbing the count when you run the the weather script…
#get rain amount
rain_file = open("/home/pi/rain_count.txt")
rain_gauge = rain_file.readline()

rain_count = int(rain_gauge)

rain_count =float(rain_count) * .02

rain_count = round(rain_count, 1)

The only thing I’ll mention here since it’s pretty straight forward is that you’ll notice I do a round at the end. I’ve experienced some false positives during the day when it’s sunny (usually 1 or 2 a day), so I just get rid of them by rounding to the nearest 10th.

Weather Station


I know it’s been a while since I posted something, I guess it was just getting difficult to find time to post something after completing a sensor before bed. My most recent project has been building my own weather station. This sort of came from the greenhouse automation project. Once I was able to measure humidity, that was it; I wanted to measure everything else about the weather that I could.

In building this, I feel I learned a lot about some other aspects of the raspberry pi, coding and some other sensors (reed switches specifically). In some places, I kind of took the easy route and took something someone else made and re-wired it to work for me, (rain gauge & wind direction pointer) but this still involved a lot of innovation on the coding side to use it. I plan to write other posts detailing the building of the other sensors; just plan to space them out some as some of them are pretty involved. I think eventually I might make a wireless self-contained version (wifi, batteries, & solar power), but that’ll be a while 😉

Oh…..forgot to mention the first time I published it…..you can see the current weather at my house by clicking on the “Current Weather” page on my blog…

Today, I put the cover on the greenhouse to get ready for the winter. I know it’s a couple weeks early (as I don’t think we have the first frost here in Texas until around mid to late November. This year, I decided to use zip ties instead of rope to attach all the pieces and I think it worked a lot better. For those who haven’t seen it before here is my little greenhouse with all my citrus trees…


I’ve recently came to the understanding that I probably don’t need my automatic watering system nearly as much in the winter time, so I’m not in a rush anymore to get it built. When I will need it though is next summer. Now the fact that I need it most when I don’t have the cover on the greenhouse means that I need to find a way to waterproof everything. I’ve been looking into waterproof boxes I can put the computer in and have some ideas, but one of the other things I’ll need are waterproof moisture/light sensors for the trees. I had a revelation the other day that I can probably use some PVC to accomplish this. When I was at Lowes picking up the zip ties for the greenhouse, I went to the the plumbing section and found my parts.


So, here it is, the new and improved waterproof (mostly. You can’t dip the whole thing in and expect it to survive. I haven’t really tested it’s waterproofness yet, but I believe it is)


What you’ll need (besides many of the parts from the previous sensor) are a 1 1/2″ plug & a 1 1/2″ cap. (These should fit into each other.) The plug has a flat end and the cap has a rounded end. At first I had a hard time finding something that would work. I had planned on using some 1″ pipe with caps on either end, but I just didn’t think that the cap would be the right shape. When I was about to give up, I went back through one more time and found these!!! I was pretty excited that I found this combo.


The first step to building this new sensor is to drill some holes in the cap and plug. You’ll need to drill a 7/32″ hole in the middle of both the cap and the plug. The plug also needs 2 1/8″ holes drilled on either side of the middle hole for the moisture sensor wire. The middle hole of the plug is for the cat 5 cable and the middle hole in the cap is for the light sensor.


Again like the previous sensor, you’ll need to use some 12 gauge wire (10″ of romex is what I use). Remove some of the insulation from both sides like before and put some solder (tin) the side that will go into the dirt. When this is complete you’ll need to make your wires look like the above picture. The way to do this is the put the wire through it’s hole and then press the end against the side of the plug and hold it there. While holding the inside, bend the outside. You’ll want the part of the wire that has the insulation removed to be above the end of the plug. (I think this is shown later).


After you have the wires bent to the correct shape, you’ll need to “attach” the probes to the plug. Put them through the hole and then place some hot glue at around the probe where it meets the hole.


Next, flip the plug over and put a good amount of glue in the plug to hold the wire in place. (You can see in this picture how I said to place the part of the wire with the insulation removed above the top of the plug.) Do this with both sides one side at a time.


Now we go to the wiring part. Just like in the previous sensor, we’ll need a LDR and a 10 ohm resistor. Green to one side of the LDR, blue and one side of the 10 ohm resistor to the other side of the LDR, and green/white to the other side of the 10 ohm resistor. Solidify this connections with some solder and cover them with some shrink tube. (Make sure when you remove the insulation from the cat 5 cable that you have a good amount to work with.)


The next step is really annoying. You need to place the LDR in the hole in the cap and secure it. Do do this, I pushed the LDR through the hole and used some hot glue to tack it down. (Wait for it to dry so you have some hold.) Once it’s try, turn it over and place a lot of hot glue into the cap. Let this dry, then fill in the holes around the LDR on the other side of the cap. (It took me 5 tries to get this right.


Almost finished. Lets solder the brown wire to the black probe and the brown/white wire to the white probe. Should be pretty easy if you gave yourself enough wire and placed the top of the probe above the top of the plug. After you finished this you can carefully press the plug inside the cap. Once together, hot glue around where the cat 5 cable went enters the plug.



Finally, just as last time, place the rj45 jack on the end. I use the above pattern even though it doesn’t match the “standard” ethernet pattern. I’ve had this sensor going all day now and it seems to be working fine. I’d like to make another one to have two to test. I’ll need to do this fairly quickly as it’s getting close to when I need to take the system outside and actually work…

Halloween Costume

For those who do not know, I have recently became a fan of Doctor Who, specifically the 11th doctor. (I have only watched episodes of the 11th, so I really can’t say I’m a fan of the others yet) Because of this I have decided to have a Halloween costume this year and I’ll be doing my best impression of the Doctor….

Now one of the driving reasons behind this, besides the new fandom high, is that I can use pieces of the costume as everyday wear. I can wear the jacket, shirt & bow tie to work and the jeans elsewhere. I could probably wear the suspenders to work and church as well, but I’m not sure I’m really a suspenders type guy. (They were free so I had no qualms about getting expensive ones. That story will be below)


For the jacket, I was able to find a used Harris tweed jacket on ebay for around $40. Now the pattern is not exact, but Hey! it’s the same material and way better than any of those $50 knockoffs they sell at the costume sites.


The shirt was probably not necessary as I could have just worn a white or cream shirt that I already have. Now that I think about it, the stripes might be a little too much and I might make a decision to not wear the shirt depending on how I look once I try it all on. (Waiting for something to come in the mail…) Its not as though the shirt will be a lost cause though. I got it on sale for 40% off from JC Penny’s and I can add it to my weekly shirt rotation.


Ah, the suspenders. A crucial part of the ensemble. I got these at the Men’s Wearhouse for FREE!!! Normally they would set you back $35. Now I know that Matt wears clips on his suspenders, but I these button ones will be close enough. The reason these were free was because I do a lot of shopping at the Men’s Wearhouse; as it is where I purchase a lot of the clothes I wear to work. For every $500 you spend, you get a $50 gift card. The one I used for this actually wasn’t because of my spend, but because I received terrible service one day and reported it to corporate and they like me as a customer so much that they gave it to me to make me happy. 🙂


The bow tie…the most crucial part of the ensemble. Bow ties are cool and we actually have a bow tie day at work occasionally. (Usually on Thursdays) I found this one on eBay for about $7.50 with shipping. I really wanted a simple burgundy one and this fits the bill.


As for the jeans, I just picked up some cheap black faded glory ones from Wal-Mart for $10. Nothing too exciting. They are relaxed fit instead of skinny jeans though.

The last piece is the boots. I didn’t buy any boots as I couldn’t see spending $40 on something that I wouldn’t normally wear. (The $40 is in reference to some I found on eBay that would probably fit the bill) So I’ll be wearing some black golf shoes…

(I didn’t forget the screwdriver, so don’t worry….)

Python Code

So, I finally got around to cleaning up the code a bit and commenting it in order to share it. First off, this is not in any way professional or “clean”. It is just me throwing some stuff down to get it to work. I am not really an OO guy; I think procedurally and so that’s how I code. I have borrowed pieces from others, specifically from Adafruit (the ADC reading code) and I do realize I could be using a lot of loops to run through things, but hey, I’m not worried about size, speed, or cleanliness; just that it works. 🙂 If you are going to use this, be aware of 3 things:
1. You’ll need to sign up for your own API from Weather Underground.
2. You’ll need make sure you’ve installed all the necessary libraries on your Pi. (Read Adafruit’s reading analog data tutorial for this piece. I’ll try to put something together in order to show all of the steps necessary to get this to work.)
3. You’ll need to change your MySQL connection variables

So without further adieu:

#!/usr/bin/env python
import time
import os
import RPi.GPIO as GPIO
import MySQLdb
import urllib2

#set up some GPIO settings

# set up pin that provides power to moisture probes
GPIO.setup(17, GPIO.OUT)
GPIO.output(17, True)

#read inside temperature sensor. temperature = temp in degrees C
tfile = open("/sys/bus/w1/devices/28-000004d608e1/w1_slave")
text = tfile.read()
temperaturedata = text.split("\n")[1].split(" ")[9]
temperature = float(temperaturedata[2:])
temperature = temperature / 1000

#go get outside humidity from weather underground using api
#reading json file to line that contains humidity and pulling
#out the numbers in the text
req = urllib2.Request('http://api.wunderground.com/api/****************/conditions/q/TX/Forney.json')
response = urllib2.urlopen(req)

read_until = 52
humid_line = 54

correctline = []
correct_humid_line = []
lines = []

for line_number, line in enumerate(response.readlines()):
if line_number == read_until:
elif line_number == humid_line:

pull_humid = ','.join(correct_humid_line)

out_humid = pull_humid[-6:-4]
out_humid = round(float(out_humid),1)

# convert celsius to fahrenheit for inside temp
temp_F = ( temperature * 9.0 / 5.0 ) + 32

# show only one decimal place for temperature
temp_F = "%.1f" % temp_F
temp_C = temperature

# read SPI data from MCP3008 chip, 8 possible adc's (0 thru 7)
def readadc(adcnum, clockpin, mosipin, misopin, cspin):
if ((adcnum > 7) or (adcnum < 0)): return -1 GPIO.output(cspin, True) GPIO.output(clockpin, False) # start clock low GPIO.output(cspin, False) # bring CS low commandout = adcnum commandout |= 0x18 # start bit + single-ended bit commandout <<= 3 # we only need to send 5 bits here for i in range(5): if (commandout & 0x80): GPIO.output(mosipin, True) else: GPIO.output(mosipin, False) commandout <<= 1 GPIO.output(clockpin, True) GPIO.output(clockpin, False) adcout = 0 # read in one empty bit, one null bit and 10 ADC bits for i in range(12): GPIO.output(clockpin, True) GPIO.output(clockpin, False) adcout <<= 1 if (GPIO.input(misopin)): adcout |= 0x1 GPIO.output(cspin, True) adcout /= 2 # first bit is 'null' so drop it return adcout # change these as desired - they're the pins connected from the # SPI port on the ADC to the Cobbler. Since I am using 2 ADCs #I have 2 chip select pins. 25 for the first one and 8 for the #second one SPICLK = 18 SPIMISO = 23 SPIMOSI = 24 SPICS = 25 SPICS1 = 8 # set up the SPI interface pins GPIO.setup(SPIMOSI, GPIO.OUT) GPIO.setup(SPIMISO, GPIO.IN) GPIO.setup(SPICLK, GPIO.OUT) GPIO.setup(SPICS, GPIO.OUT) GPIO.setup(SPICS1, GPIO.OUT) # set up the pin locations of the different probes. Can only be #0-7 as there are only 8 pins per ADC readadc0 = 0 readadc2 = 2 readadc3 = 3 readadc4 = 4 readadc5 = 5 readadc6 = 6 readadc7 = 7 readadc8 = 0 readadc9 = 1 readadc10 = 2 readadc11 = 3 readadc12 = 4 readadc13 = 5 readadc15 = 7 # read the analog pins. Assigning reads to sensor variables lux_sens0 = readadc(readadc0, SPICLK, SPIMOSI, SPIMISO, SPICS) moisture_sens1 = readadc(readadc2, SPICLK, SPIMOSI, SPIMISO, SPICS) lux_sens1 = readadc(readadc3, SPICLK, SPIMOSI, SPIMISO, SPICS) moisture_sens2 = readadc(readadc4, SPICLK, SPIMOSI, SPIMISO, SPICS) lux_sens2 = readadc(readadc5, SPICLK, SPIMOSI, SPIMISO, SPICS) moisture_sens3 = readadc(readadc6, SPICLK, SPIMOSI, SPIMISO, SPICS) lux_sens3 = readadc(readadc7, SPICLK, SPIMOSI, SPIMISO, SPICS) moisture_sens4 = readadc(readadc8, SPICLK, SPIMOSI, SPIMISO, SPICS1) lux_sens4 = readadc(readadc9, SPICLK, SPIMOSI, SPIMISO, SPICS1) moisture_sens5 = readadc(readadc10, SPICLK, SPIMOSI, SPIMISO, SPICS1) lux_sens5 = readadc(readadc11, SPICLK, SPIMOSI, SPIMISO, SPICS1) moisture_sens6 = readadc(readadc12, SPICLK, SPIMOSI, SPIMISO, SPICS1) lux_sens6 = readadc(readadc13, SPICLK, SPIMOSI, SPIMISO, SPICS1) humid_sens = readadc(readadc15, SPICLK, SPIMOSI, SPIMISO, SPICS1) # convert reading from humidity sensor to humidity based on formula # from datasheet sensor_humid = (((humid_sens*3.3/1023/3.3)-.1515)/.00636) humid = sensor_humid /(1.0546 - .00216 * float(temp_C)) inhumid = round(humid,1) # convert lux into relative terms #lux0 if lux_sens0 < 10: lux0 = "Dark" elif lux_sens0 < 200: lux0 = "Dim" elif lux_sens0 < 500: lux0 = "Light" elif lux_sens0 < 800: lux0 = "Bright" else: lux0 = "Very Bright" #lux1 if lux_sens1 < 10: lux1 = "Dark" elif lux_sens1 < 200: lux1 = "Dim" elif lux_sens1 < 500: lux1 = "Light" elif lux_sens1 < 800: lux1 = "Bright" else: lux1 = "Very Bright" #lux2 if lux_sens2 < 10: lux2 = "Dark" elif lux_sens2 < 200: lux2 = "Dim" elif lux_sens2 < 500: lux2 = "Light" elif lux_sens2 < 800: lux2 = "Bright" else: lux2 = "Very Bright" #lux3 if lux_sens3 < 10: lux3 = "Dark" elif lux_sens3 < 200: lux3 = "Dim" elif lux_sens3 < 500: lux3 = "Light" elif lux_sens3 < 800: lux3 = "Bright" else: lux3 = "Very Bright" #lux4 if lux_sens4 < 10: lux4 = "Dark" elif lux_sens4 < 200: lux4 = "Dim" elif lux_sens4 < 500: lux4 = "Light" elif lux_sens4 < 800: lux4 = "Bright" else: lux4 = "Very Bright" #lux5 if lux_sens5 < 10: lux5 = "Dark" elif lux_sens5 < 200: lux5 = "Dim" elif lux_sens5 < 500: lux5 = "Light" elif lux_sens5 < 800: lux5 = "Bright" else: lux5 = "Very Bright" #lux6 if lux_sens6 < 10: lux6 = "Dark" elif lux_sens6 < 200: lux6 = "Dim" elif lux_sens6 < 500: lux6 = "Light" elif lux_sens6 < 800: lux6 = "Bright" else: lux6 = "Very Bright" # convert moisture into relative terms # moisture1 if moisture_sens1 < 150: moisture1 = "Dry" elif moisture_sens1 < 350: moisture1 = "Moist" else: moisture1 = "Wet" # moisture2 if moisture_sens2 < 150: moisture2 = "Dry" elif moisture_sens2 < 350: moisture2 = "Moist" else: moisture2 = "Wet" # moisture3 if moisture_sens3 < 150: moisture3 = "Dry" elif moisture_sens3 < 350: moisture3 = "Moist" else: moisture3 = "Wet" # moisture4 if moisture_sens4 < 150: moisture4 = "Dry" elif moisture_sens4 < 350: moisture4 = "Moist" else: moisture4 = "Wet" # moisture5 if moisture_sens5 < 150: moisture5 = "Dry" elif moisture_sens5 < 350: moisture5 = "Moist" else: moisture5 = "Wet" # moisture6 if moisture_sens6 < 150: moisture6 = "Dry" elif moisture_sens6 < 350: moisture6 = "Moist" else: moisture6 = "Wet" # get temp from outside sensor. Needed to do this down lower # as to not get readings from sensors confused # they are attached to the same pin tfile1 = open("/sys/bus/w1/devices/28-000004cfffc6/w1_slave") text1 = tfile1.read() tfile1.close() temperaturedata1 = text1.split("\n")[1].split(" ")[9] temperature1 = float(temperaturedata1[2:]) temperature1 = temperature1 / 1000 temp_F1 = ( temperature1 * 9.0 / 5.0 ) + 32 temp_F1 = "%.1f" % temp_F1 #set in and out temps to variables I can understand in_temp = temp_F out_temp = temp_F1 #printing out the readings. Not needed, but used for testing purposes print("temp_F:", temp_F) print("temp_F1:", temp_F1) print("lux0:", lux0) print("moisture1:", moisture1) print("lux1", lux1) print("moisture2:", moisture2) print("lux2", lux2) print("moisture3:", moisture3) print("lux3", lux3) print("moisture4:", moisture4) print("lux4", lux4) print("moisture5:", moisture5) print("lux5", lux5) print("moisture6:", moisture6) print("lux6", lux6) print("Inside humid:", round(inhumid,1), "%") print("Outside humid:", round(float(out_humid),1), "%") print("moisture_sens1:", moisture_sens1) print("moisture_sens2:", moisture_sens2) print("moisture_sens3:", moisture_sens3) print("moisture_sens4:", moisture_sens4) print("moisture_sens5:", moisture_sens5) print("moisture_sens6:", moisture_sens6) #setting the pin that provides the power to the moisture sensors # to an input as to not provide power in between readings GPIO.output(17, False) GPIO.cleanup() #setting up pin for heater switch power_pin = 22 GPIO.setup(power_pin, GPIO.OUT) GPIO.setup(power_pin, False) # if temperature is below a certain point, turn the heater on if float(temp_F1) < 50: GPIO.output(power_pin, True) htr_status = "ON" else: GPIO.output(power_pin, False) htr_status = "OFF" print("heater", htr_status) #setting up pin for pump switch pump_pin = 11 GPIO.setup(pump_pin, GPIO.OUT) GPIO.setup(pump_pin, False) #check to see how many moisture sensors are reading as "Dry" moisture_count = 0 if moisture1 == "Dry": moisture_count = moisture_count + 1 if moisture2 == "Dry": moisture_count = moisture_count + 1 if moisture3 == "Dry": moisture_count = moisture_count + 1 if moisture4 == "Dry": moisture_count = moisture_count + 1 if moisture5 == "Dry": moisture_count = moisture_count + 1 if moisture6 == "Dry": moisture_count = moisture_count + 1 # if more than a certain amount of sensor read "Dry", then turn on the pump if float(moisture_count) > 1:
GPIO.output(pump_pin, True)
pump_status = "ON"
GPIO.output(pump_pin, False)
pump_status = "OFF"

print("pump status:", pump_status)

# alarm setup if pump is not coming on. (Will use this later when I
# add the float sensor to the rain barrel to make sure the pump
# doesn't come on when there's no water.) This will act as my alarm
# if there is no water in the barrel
if moisture_count > 3 and pump_status == "OFF":
moisture_alarm = "ON"
moisture_alarm = "OFF"

# Placing data into the database

# Open database connection
db = MySQLdb.connect(host="IP Address", port=3306, user= "user_name", passwd="Password" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# Prepare SQL query to INSERT a record into the database.
sql = "INSERT INTO weather_tracking.weather_results (inside_temp, outside_temp, inside_humid, outside_humid, lux0_value, lux0_txt, moisture1_value, moisture1_txt, lux1_value, lux1_txt, moisture2_value, moisture2_txt, lux2_value, lux2_txt, moisture3_value, moisture3_txt, lux3_value, lux3_txt, moisture4_value, moisture4_txt, lux4_value, lux4_txt, moisture5_value, moisture5_txt, lux5_value, lux5_txt, moisture6_value, moisture6_txt, lux6_value, lux6_txt, pump_status, htr_status, moisture_count, moisture_alarm) VALUES (" + str(in_temp) + "," + str(out_temp) + "," +str(inhumid) + "," + str(out_humid) + "," + str(lux_sens0) + ",'" + str(lux0) + "'," + str(moisture_sens1) + ",'" + str(moisture1) + "'," + str(lux_sens1) + ",'" + str(lux1) + "'," + str(moisture_sens2) + ",'" + str(moisture2) + "'," + str(lux_sens2) + ",'" + str(lux2) + "'," + str(moisture_sens3) + ",'" + str(moisture3) + "'," + str(lux_sens3) + ",'" + str(lux3) + "'," + str(moisture_sens4) + ",'" + str(moisture4) + "'," + str(lux_sens4) + ",'" + str(lux4) + "'," + str(moisture_sens5) + ",'" + str(moisture5) + "'," + str(lux_sens5) + ",'" + str(lux5) + "'," + str(moisture_sens6) + ",'" + str(moisture6) + "'," + str(lux_sens6) + ",'" + str(lux6) + "','" + str(pump_status) + "','" + str(htr_status) + "'," + str(moisture_count) + ",'" + str(moisture_alarm) + "')"
print("sql:", sql)
# Execute the SQL command
# Fetch all the rows in a list of lists.
# print "Error: Unable to Insert Data"

# disconnect from server

Such a marvelous little computer…



Today I took a half day off and finished the greenhouse automation system enough to start testing it. Here it is ready to go.



Once I got it putting the data in the database I had to put together some web pages so I could keep track of what was going on. Come to find out one of my light sensors is messed up, so I’m going to make another. Back to the web tracking, you can see now there’s a link on the blog called “Greenhouse Conditions”. This shows all the data being collected now during the testing and it will be where I can check on it when it’s actually out there during the winter.

More sensors and etc…

Today I worked on completing the rest of my moisture sensors and then worked on some other sensors and things. This included the outside temp sensor, the main light sensor (as opposed to the individual ones for each tree) and connection of the powerswitch tail.


The light sensor is on the right and the temp sensor is the metal rod on top. (You should be able to pick out the powerswitch tail from a precious post.) I decided to use an rj11 jack (phone jack) vs a rj45 (Ethernet jack) as at most I had 3 wires to deal with. I’ll review how I made the light sensor as it is the most difficult of the three.


To make this you’ll need a LDR, a 10k ohm resistor, some phone cable, a rj11 jack (rj12 will work too), and some shrink tubes.


For the tools you’ll need…a soldering iron and solder, some crimpers and strippers, a lighter, some scissors, a vice and a volt meter for testing.


To start, strip off the protective sheathing and strip the black, red, and green wires. Connect the red wire to one side of the LDR, the green and the 10k ohm resistor to the other, and the black wire to the other side of the resistor. Be sure to place some shrink tube on the red wire prior to attaching the LDR to the wire.


Next solder all the connections and place the shrink tube over the connection for the red wire and over the black wire and end of the resistor.


Next place a larger piece of shrink tube over the whole wire and shrink it on to make sure the connections are undisturbed.


After that side is completed, we need to add the jack to the other side. Strip back some of the sheathing on the cable and place your wires in this order (actually order doesn’t matter, but this is the order I use. )


Make sure that your wires are all the same length and place them in the jack. Use your crimper to attach the jack to the wire. Now we should test our sensor.


I forgot to include alligator clips in my tools pic, but they are very helpful for this step. To test I used a keystone jack connector and attached the wires shown to the correct place on the jack. I know this makes little sense, but green is red, white green is black, and orange is green. Connect the alligator clips to the wires and voltmeter. Set the voltmeter to 1M ohms resistance.



The images above show what you should be seeing when exposing your sensor to light or dark. As seen in the first image, you should get a fairly low reading when the sensor is exposed to light. When it is dark, the resistance goes very high and it will show the 0 as the voltmeter cannot read that high. (I think the LDRs I have are 10m ohms in the dark).

This sensor is going to give me a good idea of the overall light my trees receive and will be attached to the upside down basket that I use to protect the temp and humidity sensors from the sun. This sensor, like the individual tree LDRs that are in the moisture sensors gets plugged into a ADC. (Red wire is +3 volts, black is ground, and green is data and goes to ADC) Its pretty easy to use this sensor and when I get to my coding post I’ll show you the code required.

Tomorrow is softball and I won’t have any time to work on my project so I might post about growing wheat….

A Little Bit of Future Plans

Since I still have some work to go to have my sensors and everything working fully, I thought I’d talk a little about some of my later plans, particularly automatic watering.

As I’ve said previously, my current greenhouse automation will turn the heater on when it gets too cold, but that’s it. Now that’s very useful and saves a lot of electricity over me having to go out there and turn it on and off when it needs to be done. To accomplish this, I have a power switch tail hooked up to my system that basically is a switch that switches 110 volts with only 3v. This is a pretty simple device to use, you plug one end into a socket (I use an extension cord), then plug the device into the other end. Next, you plug some wires from your micro controller (or in my case your micro computer) into the power and ground in the power switch tail.


Since I am able to control 110v devices with this device I can control a pump to move water from one place to another. So, my plan is to place a electric pump in a rain barrel and turn it on when the moisture level in the planters indicates that the soil is dry. I’ll hook the pump up to a drip system that will drip on all the trees.



This is the rain barrel and pump I plan on getting to accomplish this. I should be able to get both for maybe a little over $100. The one thing I kind of worry about is that the rain barrel only holds around 50 gallons and the pump will pump around 20 gallons per minute. I have to find out if there is a way I can tone it down a bit.


The other thing I have thought about is not wanting the pump to run when there is no water in the barrel. To do this I can use this float switch. When the water is below a certain level in the barrel I will set the code to not turn the pump on. I’ll have to drill a hole in the barrel to install it, but it should be easy to attach it to the ADC to determine if the switch is open or closed. I plan on running the program every 5 minutes to do all the logging and checking of the sensors.

Moisture Sensor Circuit

Tonight I thought I would post on how the rest of the moisture sensor circuit works since I think I have it going correctly now. I was using a transistor that was switched by a digital pin when it was time to run the program, but when I put it all together to test, it didn’t work at all. So this is what I have at the moment; which seems to work with the two sensors I have built right now. More testing will be required after everything is completed.


The first thing you’ll need is the rj45 female jack to plug your sensor into. Remember your order from previously as you’ll need to know which pins do what in your sensor.

When I created my sensors I used brown for into the moisture sensor, brown and white as out of the moisture sensor. Green was plus volts for the LDR and green and white is the ground side. The blue wire is the data wire; which leads us to the next step.


From looking at my plug and memory, I know that pin 3 should be data for the LDR. I run a wire from pin 3 to my analog input. (I use a raspberry pi so I have to have an ADC (analog to digital converter) to convert the analog signals from the sensor to something the pi can understand.


The next pin is pin 5 which is the brown wire or plus volts to the sensor. I connect this to a digital pin on my pi and in my code only set it to high (or power) when I need to so I don’t experience as much electrolysis. (I’ll show this in the code later.)


Next is pin 6 which is brown and white or the other side of the sensor. This also needs to be connected to an analog input

This should tell you how much moisture is in the soil by the amount of volts that transverse the sensor.


The next thing you’ll need to do is to put a pull down resistor on the yellow wire to ground. This is to pull the voltage reading down to zero when there is nothing going on with the sensor. I use a 10k ohm resistor for this



The last step is to connect pins 7 and 8 appropriately. Pin 7 is the green wire or power for the LDR (goes to +volts and pin 8 is the green and white wire ( aka ground for the LDR)

I still have a good amount of work to complete the automation system, but it seems to be coming along quite nicely.

Tomorrow I may show the code to
see how the relative moisture is captured or I may go to a different sensor (humidity, temperature, etc…)