PiPlanter 2 | New Code Version / Temporary Setup

Hello! Here are some images of the new grow setup:

and here is the working version of the code:


import time
from time import sleep
from time import strftime

import tweepy
consumer_key=""
consumer_secret=""
access_token=""
access_token_secret=""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

PiPlanter_Full = False

import logging
logging.basicConfig()
from apscheduler.scheduler import Scheduler

import os
import sys

import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)

# Start of mysql setup
import MySQLdb
user = MySQLdb.connect(host="localhost",user="root",passwd="")
cursor = user.cursor()

MySQLdb_Name = 'PiPlanter' + strftime("_%m_%d_%Y_%I_%M_%S%p")
mysql_table_name = MySQLdb_Name + '_table'

mysql_create = 'CREATE DATABASE IF NOT EXISTS PiPlanter' 
mysql_grant = "GRANT ALL ON `" + MySQLdb_Name + "`.* TO 'piplanter'@'localhost' IDENTIFIED BY 'password'"
mysql_use = 'USE PiPlanter' 

if PiPlanter_Full == True:
	#Full PiPlanter
	mysql_table = "CREATE TABLE " + mysql_table_name + "(Sample_Number INT NOT NULL AUTO_INCREMENT PRIMARY KEY,Time VARCHAR(100),P_TMP0 VARCHAR(100),P_MST0 VARCHAR(100),P_TMP1 VARCHAR(100),P_MST1 VARCHAR(100),P_TMP2 VARCHAR(100),P_MST2 VARCHAR(100),P_TMP3 VARCHAR(100),P_MST3 VARCHAR(100),A_TMP0 VARCHAR(100),A_LDR0 VARCHAR(100),A_LDR1 VARCHAR(100),A_MST0 VARCHAR(100))"
else:
	#Simple PiPlanter
	mysql_table = "CREATE TABLE " + mysql_table_name + "(Sample_Number INT NOT NULL AUTO_INCREMENT PRIMARY KEY,Time VARCHAR(100),P_MST0 VARCHAR(100),P_MST1 VARCHAR(100),A_TMP0 VARCHAR(100),A_LDR0 VARCHAR(100))"

#A new database must be created each time the program runs
cursor.execute(mysql_create)
cursor.execute(mysql_grant)
cursor.execute(mysql_use)
cursor.execute(mysql_table)

pins = {'MST_Enable' : 8} #assign names to GPIO pins
for d in pins.itervalues():
	GPIO.setup(d,GPIO.OUT)

#first ADC setup on SPI port 1
import spidev
spi_1 = spidev.SpiDev()
spi_1.open(0, 1)

#first ADC setup on SPI port 0
import spidev
spi_0 = spidev.SpiDev()
spi_0.open(0, 0)

#this function can be used to find out the ADC value on ADC 0
def readadc_0(adcnum_0): 
    if adcnum_0 > 7 or adcnum_0 < 0:
        return -1
    r_0 = spi_0.xfer2([1, 8 + adcnum_0 << 4, 0])
    adcout_0 = ((r_0[1] & 3) << 8) + r_0[2]
    return adcout_0

#this function can be used to find out the ADC value on ADC 1
def readadc_1(adcnum_1): 
    if adcnum_1 > 7 or adcnum_1 < 0:
        return -1
    r_1 = spi_1.xfer2([1, 8 + adcnum_1 << 4, 0])
    adcout_1 = ((r_1[1] & 3) << 8) + r_1[2]
    return adcout_1
  
#this function converts a given value from the ADC and turns it into usable data
def convertadc(adcinput,unit):
	millivolts = adcinput*(3300.0/1024.0) #converts the ADC value to milivolts
	temp_c = ((millivolts - 100.0)/10)-40.0
	percent = (adcinput/1024.0)*100
	if unit == 'c' : #used for a temperature sensor to return Celsius 
		return temp_c
	elif unit == 'f' :  #used for a temperature sensor to return Fahrenheit  
		temp_f = (temp_c * 9.0 / 5.0) + 32
		return temp_f
	elif unit == 'mV':
		return millivolts
	elif unit == '%':
		return percent
	else:
		print "convertadc input error"
		return 0

#returns a usable numerical value from the ADC
def pollsensor(sensor,unit,precision,samples):
	GPIO.output(pins['MST_Enable'], True)
	if PiPlanter_Full == True:
		#Full PiPlanter
		sensors = {\
		'P_TMP0' : convertadc(readadc_0(0),unit),\
		'P_MST0' : convertadc(readadc_0(1),unit),\
		'P_TMP1' : convertadc(readadc_0(2),unit),\
		'P_MST1' : convertadc(readadc_0(3),unit),\
		'P_TMP2' : convertadc(readadc_0(4),unit),\
		'P_MST2' : convertadc(readadc_0(5),unit),\
		'P_TMP3' : convertadc(readadc_0(6),unit),\
		'P_MST3' : convertadc(readadc_0(7),unit),\
	
		'A_TMP0' : convertadc(readadc_1(0),unit),\
		'A_LDR0' : convertadc(readadc_1(1),unit),\
		'A_LDR1' : convertadc(readadc_1(2),unit),\
		'A_MST0' : convertadc(readadc_1(3),unit)}
	else:
		#Simple PiPlanter
		sensors = {\
		'P_MST0' : convertadc(readadc_0(0),unit),\
		'P_MST1' : convertadc(readadc_0(1),unit),\
		'A_TMP0' : convertadc(readadc_0(2),unit),\
		'A_LDR0' : convertadc(readadc_0(3),unit)}
	
	outputsum = 0
	for x in range(0,samples): #An averaging algorithm that creates a more precise reading
		outputsum = outputsum + sensors[sensor]
	output = round(outputsum/samples, precision)
	GPIO.output(pins['MST_Enable'], False)
	return output

#samples all sensors, outputs different formats of the data to be used in other places in the program
def sampleallsensors(sensor_precision,sensor_samples,form):	
	if PiPlanter_Full == True:
		#Full PiPlanter
		current_sensors = {\
		'P_TMP0' : pollsensor('P_TMP0' , 'f', sensor_precision, sensor_samples),\
		'P_MST0' : pollsensor('P_MST0' , '%', sensor_precision, sensor_samples),\
		'P_TMP1' : pollsensor('P_TMP1' , 'f', sensor_precision, sensor_samples),\
		'P_MST1' : pollsensor('P_MST1' , '%', sensor_precision, sensor_samples),\
		'P_TMP2' : pollsensor('P_TMP2' , 'f', sensor_precision, sensor_samples),\
		'P_MST2' : pollsensor('P_MST2' , '%', sensor_precision, sensor_samples),\
		'P_TMP3' : pollsensor('P_TMP3' , 'f', sensor_precision, sensor_samples),\
		'P_MST3' : pollsensor('P_MST3' , '%', sensor_precision, sensor_samples),\
		'A_TMP0' : pollsensor('A_TMP0' , 'f', sensor_precision, sensor_samples),\
		'A_LDR0' : pollsensor('A_LDR0' , '%', sensor_precision, sensor_samples),\
		'A_LDR1' : pollsensor('A_LDR1' , '%', sensor_precision, sensor_samples),\
		'A_MST0' : pollsensor('A_MST0' , '%', sensor_precision, sensor_samples)}
	else:
		#Simple PiPlanter
		current_sensors = {\
		'P_MST0' : pollsensor('P_MST0' , '%', sensor_precision, sensor_samples),\
		'P_MST1' : pollsensor('P_MST1' , '%', sensor_precision, sensor_samples),\
		'A_TMP0' : pollsensor('A_TMP0' , 'f', sensor_precision, sensor_samples),\
		'A_LDR0' : pollsensor('A_LDR0' , '%', sensor_precision, sensor_samples)}
	
	if form == 'MySQL':
		if PiPlanter_Full == True:
			#Full PiPlanter
			output = "INSERT INTO " + mysql_table_name + "(Time, P_TMP0, P_MST0, P_TMP1, P_MST1, P_TMP2, P_MST2, P_TMP3, P_MST3, A_TMP0, A_LDR0, A_LDR1, A_MST0)" + " VALUES(NOW()" + "," + str(current_sensors['P_TMP0']) + "," + str(current_sensors['P_MST0']) + "," + str(current_sensors['P_TMP1']) + "," + str(current_sensors['P_MST1']) + "," + str(current_sensors['P_TMP2']) + "," + str(current_sensors['P_MST2']) + "," + str(current_sensors['P_TMP3']) + "," + str(current_sensors['P_MST3']) + "," + str(current_sensors['A_TMP0']) + "," + str(current_sensors['A_LDR0']) + "," + str(current_sensors['A_LDR1']) + "," + str(current_sensors['A_MST0']) + ")"  
		else:
			#Simple PiPlanter
			output = "INSERT INTO " + mysql_table_name + "(Time, P_MST0, P_MST1, A_TMP0, A_LDR0)" + " VALUES(NOW()" + "," + str(current_sensors['P_MST0']) + "," + str(current_sensors['P_MST1']) + "," + str(current_sensors['A_TMP0']) + "," + str(current_sensors['A_LDR0']) + ")"  
	elif form == 'Console':
		if PiPlanter_Full == True:
			#Full PiPlanter
			output = 'Debug Update:' + ' P_TMP0: ' + str(str(current_sensors['P_TMP0'])) + ',' + ' P_MST0: ' + str(str(current_sensors['P_MST0'])) + ',' + ' P_TMP1: ' + str(str(current_sensors['P_TMP1'])) + ',' + ' P_MST1: ' + str(str(current_sensors['P_MST1'])) + ','+ ' P_TMP2: ' + str(str(current_sensors['P_TMP2'])) + ','+ ' P_MST2: ' + str(str(current_sensors['P_MST2'])) + ','+ ' P_TMP3: ' + str(str(current_sensors['P_TMP3'])) + ','+ ' P_MST3: ' + str(str(current_sensors['P_MST3'])) + ',' + ' A_TMP0: ' + str(str(current_sensors['A_TMP0'])) + ',' + ' A_LDR0: ' + str(str(current_sensors['A_LDR0'])) + ','+ ' A_LDR1: ' + str(str(current_sensors['A_LDR1'])) + ','+ ' A_MST0: ' + str(str(current_sensors['A_MST0'])) 	
		else:
			#Simple PiPlanter
			output = 'Debug Update:' + ' P_MST0: ' + str(str(current_sensors['P_MST0'])) + ',' + ' P_MST1: ' + str(str(current_sensors['P_MST1'])) + ',' + ' A_TMP0: ' + str(str(current_sensors['A_TMP0'])) + ',' + ' A_LDR0: ' + str(str(current_sensors['A_LDR0'])) 	
	elif form == 'Twitter':
		if PiPlanter_Full == True:
			#Full PiPlanter
			output = 'Ambient LDR: ' + str(round(((current_sensors['A_LDR0'] + current_sensors['A_LDR1'])/2),1) ) + '%, ' + 'Ambient Tmp: ' + str(round(current_sensors['A_TMP0'],1)) + 'DF, ' + 'Average Plant Tmp: ' + str(round( (current_sensors['P_TMP0'] + current_sensors['P_TMP1'] + current_sensors['P_TMP2'] + current_sensors['P_TMP3'] )/4, sensor_precision-2)) + 'DF, ' + 'Ambient Mst: ' + str(round(current_sensors['A_MST0'],2)) + '%, ' + 'Average Plant Mst: ' + str(round( (current_sensors['P_MST0']+current_sensors['P_MST1']+ current_sensors['P_MST2']+ current_sensors['P_MST3'] )/4 ,1)) + '%'
		else:
			#Simple PiPlanter
			output = 'Ambient Light: ' + str(round((current_sensors['A_LDR0']),1)) + '%, ' + 'Ambient Temp: ' + str(round(current_sensors['A_TMP0'],1)) + 'DF, ' + 'Average Plant Mst: ' + str(round( (current_sensors['P_MST0']+current_sensors['P_MST1'])/2 ,1)) + '%'
	else:
		print "convertadc input sampleallsensors"
		return 0
	return output
	
pumps = {'PUMP0' : 7, 'PUMP1' : 11, 'PUMP2' : 13, 'PUMP3' : 16} #assign names to GPIO pins
for k in pumps.itervalues():
	GPIO.setup(k,GPIO.OUT)

#pumps a given amount of water from a given pump
def pumpwater(pump,volume):
	LPM = 4.00 #L per minute
	ontime = volume*(60/LPM)
	GPIO.output(pumps[pump],True)
	time.sleep(ontime)
	GPIO.output(pumps[pump],False)
	output = 'Pumped ' + str(volume) + ' L  of water into plants in ' + str(ontime) + ' seconds.'
	return output

#Sets up proper directories for folders and images
def visualssetup(time):
	#checks if directories above exist
	if not os.path.exists(str(os.getcwd()) + '/videos/'):
		os.makedirs(str(os.getcwd()) + '/videos/')

	if not os.path.exists(str(os.getcwd()) + '/videos/dailys/'):
		os.makedirs(str(os.getcwd()) + '/videos/dailys/')
	
	if not os.path.exists(str(os.getcwd()) + '/images/'):
		os.makedirs(str(os.getcwd()) + '/images/')
	
	if not os.path.exists(str(os.getcwd()) + '/images/dailys/'):
		os.makedirs(str(os.getcwd()) + '/images/dailys/')

	global current_dailypicdir
	current_dailypicdir = str(os.getcwd()) + '/images/dailys/' + str(time) + '/'
	os.makedirs(current_dailypicdir)

	global current_dailyvideodir
	current_dailyvideodir = str(os.getcwd()) + '/videos/dailys/' + str(time) + '/'
	os.makedirs(current_dailyvideodir)

def picture(dir,cycle):
	image = dir  + str(cycle).zfill(4) + '.jpg'
	picture_command = 'raspistill -o ' + dir  + str(cycle).zfill(4) + '.jpg'
	os.system(picture_command)
	return image

def rendervideo():
	time  = strftime("%m-%d-%Y_%I-%M-%S%p")
	global current_videodir
	scheduler.shutdown(shutdown_threadpool=False)
	render_command = 'sudo mencoder -nosound mf://' + current_dailypicdir + '*.jpg -mf w=2592:h=1944:type=jpg:fps=15 -ovc lavc -lavcopts vcodec=mpeg4:vbitrate=2160000:mbd=2:keyint=132:v4mv:vqmin=3:lumi_mask=0.07:dark_mask=0.2:mpeg_quant:scplx_mask=0.1:tcplx_mask=0.1:naq -o ' + current_dailyvideodir + 'output.avi'
	os.system(render_command)

def daily():
	visualssetup(strftime("%m-%d-%Y_%I-%M-%S%p"))
	api.update_status(pumpwater('PUMP0',3))
	global cycle
	cycle = 0 


def hourly():
	cursor.execute(sampleallsensors(3,20,'MySQL'))
	user.commit()

	print sampleallsensors(3,20,'Console')
	
	pumpwater('PUMP0', .5)
	
	global current_dailypicdir
	api.update_status(sampleallsensors(3,20,'Twitter') + " https://esologic.com/?page_id=1042")
	picture(current_dailypicdir,cycle)
	
	#pumpwater('PUMP0', 1)
	
	global cycle 
 	cycle = cycle + 1 
	
if __name__ == '__main__':
	
	daily()
	hourly()

	scheduler = Scheduler(standalone=True)
	scheduler.add_interval_job(hourly, hours=1)
	scheduler.add_interval_job(daily, days=1)
    
	try:
		scheduler.start()
	except (KeyboardInterrupt, SystemExit):
		pass

I’ll do a much more thorough post when the project is further along. For those playing along at home, you can see that I’ve totally re-written the code for this new version. So far, it has much less functionality but much more stability and flexibility.

PiPlanter 2 | Little Plants 1 / Germination Setup

The plants are coming along quite nicely, here is an album of images:

As for my grow setup in this stage, it’s pretty simple. Basically I keep the two desk lamps I have from that area on 24/7 and on the plants. Every morning I put about a half gallon into each of the trays. I also spray about 8oz onto the surface of the plants. Working pretty well so far, all of this growth is only after a week and two days.

PiPlanter 2 | Update / Dirt / Germs

Hi! In order to do PiPlanter 2 at the scale I want, as always, I need money. I’m applying to this grant to hopefully take this project to unreal new heights. In order to apply, one of the component is assembling a budget. In order to do that though, I need to “complete” the whole project… in my head. I have to be able to think of exactly how I want to do the project. From PCB design to pump system, I have to plan it all in order to assemble a realistic budget. There is a lot of good work that comes with this, like schematics and the budget itself. I’ll for sure upload all of the documentation.

On a more stimulating note: I’ve planted the tomato plants in the same manor that I did last summer and here are some pictures of the growth so far.

Here is the dirt and planted seeds:

Here are some very small sprouts that have developed in the last two days.

PiPlanter 2 | Getting Started Again

So I have decided to re write the PiPlanter from the ground up. In essence, it will accomplish the same exact thing but I’d like it to be a lot more of a stable platform to expand upon in the future. I’d also like PiPlanter to be professional enough to bring to market. First off there are a few things you’d need install & a few modifications you’d need to make to Raspian. First thing’s first, you’ll need to enable SPI in the kernel so:

sudo vi /etc/modprobe.d/raspi-blacklist.conf

Comment out the spi-bcm2708 line so it looks like this:

#blacklist spi-bcm2708

Then run this to make it more permanent.

sudo modprobe spi-bcm2708

Now for the real meat of it. You’ll need these packages for SPI and the WiringPi library makes things a whole lot easier for us. This program also relies very heavily

sudo apt-get install python-imaging python-imaging-tk python-pip python-dev git
sudo pip install spidev
sudo pip install wiringpi
sudo apt-get install apache2
sudo apt-get install mysql-server
sudo apt-get install php5
sudo apt-get install php5-mysql
sudo pip install tweepy</pre>
<pre style="color: #333333;">sudo pip install apscheduler</pre>
<pre>

Revised python code next post.

PiPlanter | Goals and changes

So I am 151 miles away from the PiPlanter. But thanks to the internet, modern day routers, and wifi dongles I can pretty much control everything about it from here.

That being said, there are a few things I would like to change about the project. First of all, the program itself needs to be more modular. Reason being is that the core program should never stop running, even if changes need to be made. I should be able to screen the main program once, and then never have to stop it ever. This would be advantageous in a few ways but the main example is that the plants will require more water as they get larger, and then less once they start yielding fruit. I could script this, but I think that it would be best to be able to edit the ‘ontime’ value from the program without having to stop the whole process.

I’ll keep y’all posted as I try to implement this.

Multiple Project Update

Hi guys

So I’ve been eeking out all that I can of my last few days of summer, and there hasn’t been much rain or bad weather at all. As a result, I’m not posting much at all.

Doesn’t mean I’m not working though, I’ve been doing a couple things.

First thing’s first my speaker is done. I just need to get a bunch of video edited, and a big post written.

Secondly I’m still working really hard on my dead simple flickr uploader (dsfu). The cool thing about this project is that it has the potential to be very useful to quite a number of people, so I’m trying to make sure that it is very stable, and very easy to duplicate. This means for the most part I’ve been doing a series of 4000+ photo uploads trying to break my script. It’s happened a lot, and you can check my twitter feed to see my brain melt as I try and figure out the problem. This project won’t necessarily be “complete” until I have a 3D printer at my disposal to create the enclosure I want.

As for the PiPlanter, it’s still a work in progress. The update I did with my last post was a start to something really complete it is in no way finished. I still need to move the camera, and the plants.

Thanks for reading!

PiPlanter | Big Overhaul Update

Okay! So I leave for college in less than 30 days, but I’d like to make sure my tomatoes to continue to grow once I leave so I’ve taken some steps to make sure that my departure goes smoothly.

Here’s a video of my revised setup:

There are a few key differences between this setup and my previous one:

The main one is that the watering system has been 100% re-vamped. The water distribution happens via a hose with holes in it instead of using the tray at the bottom of the plant grid in the previous video.

It also takes, uploads and tweets a picture of itself using a raspberry pi camera module.

It also creates a new mysql table every two weeks, and in turn, renders a new kind of graph. The renderscript.php file receives an argument from the python script which is the table code.

Here’s the python script:

#Timing setup
from datetime import datetime
from apscheduler.scheduler import Scheduler
import time
import datetime
import sys
import os




now =datetime.datetime.now()




#import logging #if you start getting logging errors, uncomment these two lines
#logging.basicConfig()




#GPIO setup
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.cleanup()
pin = 26 #pin for the adc
GPIO.setup(pin, GPIO.OUT)
NPNtrans = 3 #the pin for the npn transistor
GPIO.setup(NPNtrans, GPIO.OUT)
sampleLED = 5 #the indicator LED
GPIO.setup(sampleLED, GPIO.OUT)
pump = 7 #pin for the pump
GPIO.setup(pump, GPIO.OUT)
GPIO.output(pump, False)




#the adc's SPI setup
import spidev
spi = spidev.SpiDev()
spi.open(0, 0)




#sets up the program's ability to write to a mysql database
import MySQLdb
con = MySQLdb.connect('localhost','piplanter_user','piplanter_pass','piplanter');
cursor = con.cursor()




#tweepy setup, you must use the keys given to you when you create your app
import tweepy
consumer_key=""
consumer_secret=""
access_token=""
access_token_secret=""
#"logs in" to twitter, 
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)




#Flickr Setup
import flickrapi
api_key = ''
api_secret = ''
flickr = flickrapi.FlickrAPI(api_key, api_secret, format='json')
(token, frob) = flickr.get_token_part_one(perms='write')
if not token: raw_input("Press ENTER after you authorized this program")
flickr.get_token_part_two((token, frob))




#Variable Setup
ontime = 60




global table_number
table_number = 0




#fuction that can read the adc
def readadc(adcnum): 
# read SPI data from MCP3008 chip, 8 possible adc's (0 thru 7)
    if adcnum > 7 or adcnum < 0:
        return -1
    r = spi.xfer2([1, 8 + adcnum << 4, 0])
    adcout = ((r[1] & 3) << 8) + r[2]
    return adcout
     	
def water():
	
	print "===== Starting Watering Process ====="
	
	GPIO.output(NPNtrans, True)
	GPIO.output(sampleLED, True)
	
	time.sleep(1)
	
	sensor1_before = readadc(0)
	sensor2_before = readadc(1)
	sensor3_before = readadc(2)
	sensor4_before = readadc(3)
	
	before = "WATERING START / Moisture Before - " + "Sensor 1:" + str(sensor1_before) + " Sensor 2:" + str(sensor2_before) + " Sensor 3:" + str(sensor3_before) + " Sensor 4:" + str(sensor4_before) + " - Average:" + str((float(sensor1_before+sensor2_before+sensor3_before+sensor4_before)/4)) 
	api.update_status(before) 
	print before
	
	GPIO.output(pump, True)
	time.sleep(ontime)
	GPIO.output(pump, False)
	
	time.sleep(60) #gives the water time to penetrate the soil
	
	sensor1_after = readadc(0)
	sensor2_after = readadc(1)
	sensor3_after = readadc(2)
	sensor4_after = readadc(3)
	
	after = "WATERING COMPLETED / Moisture After - " + "Sensor 1:" + str(sensor1_after) + " Sensor 2:" + str(sensor2_after) + " Sensor 3:" + str(sensor3_after) + " Sensor 4:" + str(sensor4_after) + " - Average: " + str((float(sensor1_after+sensor2_after+sensor3_after+sensor4_after)/4)) 
	api.update_status(after) 
	print after
	
	GPIO.output(NPNtrans, False)
	GPIO.output(sampleLED, False)
	
	print "====== Watering Process Complete ====="    	
    	
def hourlyUpdate():
	GPIO.output(pump, False)
	print "----------start----------\n"
	
	GPIO.output(NPNtrans, True)
	GPIO.output(sampleLED, True)
	
	time.sleep(1)
	
	sampleTime = time.ctime()
	
	mst1 = 1024-readadc(0)
	mst2 = 1024-readadc(1)
	mst3 = 1024-readadc(2)
	mst4 = 1024-readadc(3)
	
	pot1 = readadc(4)
	
	ldr1 = readadc(5)
	
	millivolts = readadc(6)*(3300.0/1024.0)
	temp_c = ((millivolts - 100.0)/10)-40.0
	tmp1 = (temp_c * 9.0 / 5.0) + 32
	
	print 'Polling Probes \n'
	
	#prints debug info to console
	print sampleTime,"|","MST1:",mst1,"MST2:",mst2,"MST3:",mst3,"MST4:",mst4,"Pot1:",pot1,"LDR1:",ldr1,"TMP1:",tmp1 #prints the debug info
	
	global table_number
	print 'Adding Data To Table: ' + str(table_number)




	#adds the data to the mysql table
	global table_number
	cursor.execute('INSERT INTO piplanter_table_'+ table_code +'(Time,mst1_V,mst2_V,mst3_V,mst4_V,pot1_V,ldr1_V,tmp1_F) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)',(sampleTime,mst1,mst2,mst3,mst4,pot1,ldr1,tmp1))
	con.commit() #this is important for live updating
	GPIO.output(NPNtrans, False) #turns the probes off
	print 'Data Collected, Disengaging Probes \n'
	
	
	#takes a picture of the plants
	print 'Taking Picture with Raspberry Pi Camera Board'
	picture_dir = '/home/pi/documents/piplanter/images/'
	os.system('raspistill -o ' + picture_dir + str(time.strftime('%m-%d-%y_%H-%M-%S')) + '.jpg')
	print 'Capture Successfull: ' + picture_dir + str(time.strftime('%m-%d-%y_%H-%M-%S')) + '.jpg'
		
	#finds the newest image in the directory
	print '\nUploading Picture To Flickr'
	picture_allfiles = sorted(os.listdir(picture_dir), key=lambda p: os.path.getctime(os.path.join(picture_dir, p)))
	picture_newest = picture_dir+picture_allfiles[-1]
	print 'File for upload: ' + picture_newest #prints location and file to console
	
	#uploads the picture of the plants to flickr
	picture_title = 'Picture @ ' + str(sampleTime)
	picture_response = flickr.upload(filename=picture_newest, title=picture_title, format='etree') #uploads the file to flickr
	picture_photoID = picture_response.find('photoid').text #gets the id of the photo for constructing a url
	print 'Picture Upload Successful, Photo ID: ' + picture_photoID + '\n' #more debug info
	
	time.sleep(10)
	
	#renders the image of the graph
	print "Graph Render Start"
	global table_code
	os.system('php /opt/bitnami/wordpress/piplanter/renderScript.php ' + table_code ) #renders the .png file
	print "Graph Render Complete \n"
	
	#finds the newest image in the directory
	print 'Uploading Graph To Flickr'
	graph_allfiles = sorted(os.listdir('/opt/bitnami/wordpress/piplanter/renders/'), key=lambda p: os.path.getctime(os.path.join('/opt/bitnami/wordpress/piplanter/renders/', p)))
	graph_newest = '/opt/bitnami/wordpress/piplanter/renders/'+graph_allfiles[-1]
	print 'File for upload: ' + graph_newest #prints location and file to console
	
	graph_title = 'Graph @ ' + str(sampleTime)
	graph_response = flickr.upload(filename=graph_newest, title=graph_title, format='etree') #uploads the file to flickr
	graph_photoID = graph_response.find('photoid').text #gets the id of the photo for constructing a url
	print 'Graph Upload Successful, Photo ID: ' + graph_photoID + '\n' #more debug info
	
	#tweets the images and data
	send = 'Brghtnss: ' + str(format((((float(ldr1)/1024)*100)),'.0f')) + '% / ' + 'Tmprtr: ' + str(format(tmp1,'.0f')) + ' Dg F' + ' / Avg Plnt Moisture: '+  str(format(float((float((mst1+mst2+mst3+mst4)/4)/1024)*100),'.0f')) + '%' + ' Graph: ' + 'http://www.flickr.com/photos/97350286@N08/'+ str(graph_photoID) + ' Pic: ' + 'http://www.flickr.com/photos/97350286@N08/' + str(picture_photoID) #builds the text of the tweet
	print "Tweeting:" , send  #for debug purposes
	api.update_status(send) #tweets the tweet
		
	time.sleep(.1)
	GPIO.output(sampleLED, False)
	
	print "\n-----------end-----------"
	
def table_update():
	
	global table_number
	table_number = table_number + 1
	
	global table_code
	table_code = str(time.strftime('%m_%d_%y_%H_%M_%S')) + '__' + str(table_number)
	print 'Creating Table: ' + table_code
	cursor.execute('USE piplanter')
	con.commit()
	cursor.execute('CREATE TABLE piplanter_table_'+ table_code +'(Sample_Number INT NOT NULL AUTO_INCREMENT PRIMARY KEY, Time VARCHAR(100), mst1_V VARCHAR(100), mst2_V VARCHAR(100), mst3_V VARCHAR(100), mst4_V VARCHAR(100), pot1_V VARCHAR(100), ldr1_V VARCHAR(100), tmp1_F VARCHAR(100) );')
	con.commit()




table_update()
hourlyUpdate()
	
scheduler = Scheduler(standalone=True)




scheduler.add_interval_job(hourlyUpdate, hours=1)
scheduler.add_interval_job(water, days=1)
scheduler.add_interval_job(table_update, weeks=2)




scheduler.start() #runs the program indefianately once every hour

Here’s the .php script:

<?php

/* Include all the classes */ 
include("/srv/www/lib/pChart/class/pData.class.php");
include("/srv/www/lib/pChart/class/pDraw.class.php");
include("/srv/www/lib/pChart/class/pImage.class.php");

$myData = new pData(); /* Create your dataset object */ 

$db = mysql_connect("localhost", "piplanter_user", "piplanter_pass"); //location of server, db username, db pass
mysql_select_db("piplanter", $db);

$Requete = "SELECT * FROM `piplanter_table_" . $argv[1] . "`"; //table name
$Result = mysql_query($Requete, $db);

/*This fetches the data from the mysql database, and adds it to pchart as points*/
while($row = mysql_fetch_array($Result))
{	
	$Time = $row["Time"];
	$myData->addPoints($Time,"Time");
	
	$mst1_V = $row["mst1_V"];
	$myData->addPoints($mst1_V,"mst1_V");
	$mst2_V = $row["mst2_V"];
	$myData->addPoints($mst2_V,"mst2_V");
	$mst3_V = $row["mst3_V"];
	$myData->addPoints($mst3_V,"mst3_V");
	$mst4_V = $row["mst4_V"];
	$myData->addPoints($mst4_V,"mst4_V");
	
	$ldr1_V = $row["ldr1_V"];
	$myData->addPoints($ldr1_V,"ldr1_V");
	
	$tmp1_F = $row["tmp1_F"];
	$myData->addPoints($tmp1_F,"tmp1_F");
}

$myData-> setSerieOnAxis("tmp1_F", 0); //assigns the data to the frist axis
$myData-> setAxisName(0, "Degrees F"); //adds the label to the first axis

$myData-> setSerieOnAxis("ldr1_V", 1);
$myData-> setAxisName(1, "LDR");

$myData-> setSerieOnAxis("mst1_V", 2);
$myData-> setSerieWeight("mst1_V",2);
$myData-> setSerieOnAxis("mst2_V", 2);
$myData-> setSerieOnAxis("mst3_V", 2);
$myData-> setSerieOnAxis("mst4_V", 2);
$myData-> setAxisName(2, "Relative Moisture");

$myData->setAbscissa("Time"); //sets the time data set as the x axis label

$myData-> setSerieWeight("mst1_V",1); //draws the line tickness
$myData->setPalette("mst1_V",array("R"=>58,"G"=>95,"B"=>205,"Alpha"=>80)); //sets the line color
$myData-> setSerieWeight("mst2_V",1);
$myData->setPalette("mst2_V",array("R"=>39,"G"=>64,"B"=>139,"Alpha"=>80));
$myData-> setSerieWeight("mst3_V",1);
$myData->setPalette("mst3_V",array("R"=>0,"G"=>34,"B"=>102,"Alpha"=>80));
$myData-> setSerieWeight("mst4_V",1);
$myData->setPalette("mst4_V",array("R"=>67,"G"=>110,"B"=>238,"Alpha"=>80));

$myData-> setSerieWeight("ldr1_V",2);
$myData-> setSerieTicks("ldr1_V", 4);

$myData-> setSerieWeight("tmp1_F",2);
$myData-> setSerieTicks("tmp1_F", 4);

$myPicture = new pImage(4000,500,$myData); /* Create a pChart object and associate your dataset */ 
$myPicture->setFontProperties(array("FontName"=>"/srv/www/lib/pChart/fonts/pf_arma_five.ttf","FontSize"=>6)); /* Choose a nice font */
$myPicture->setGraphArea(130,40,3900,300); /* Define the boundaries of the graph area */
$myPicture->drawScale(array("LabelRotation"=>320)); /* Draw the scale, keep everything automatic */ 

$Settings = array("R"=>250, "G"=>250, "B"=>250, "Dash"=>1, "DashR"=>0, "DashG"=>0, "DashB"=>0);

/*The combination makes a cool looking graph*/
$myPicture->drawPlotChart(array("DisplayValues"=>TRUE));
$myPicture->drawLineChart();
$myPicture->drawLegend(30,320); //adds the legend

//$date-> date("d-M-Y:H:i:s");

//$myPicture->autoOutput(); /* Build the PNG file and send it to the web browser */ 

$myPicture->render("/opt/bitnami/wordpress/piplanter/renders/".date("d-M-Y_H:i:s").".png");

?>

Thank you for reading!