Since I returned to college the PiPlanter has been running without me having to do any maintenance on it at all. The plants are still alive and growing and all processes associated with the PiPlanter are still going. I figure now is a good a time as any to bring together all of the work I’ve done to till this point in one concise post.
This does NOT mean I’m done working on future versions of the PiPlanter. I’ll hopefully write another post stating goals for the future sometime soon. Now onto the build tutorial.
The Hardware
First, the hardware of the project. A good place to start would be the parts list:
In the previous version of the PiPlanter, I didn’t have a concrete parts list for the project. Hopefully I’ll be able to keep this spreadsheet updated if the project changes. A lot of these components are mix and match, you could use pretty much any pump (The math for volumetric pumping is done with this pump) or any tubing or any power supply that can do 12v and 5v. A computer PSU would work great as well.
This is the hookup guide for the system:
(Thanks to tamps for the help!)
The two sets of header blocks are to be replaced by the moisture sensors, and the motor replaced with the pump.
For a physical configuration, I’ve found through multiple times doing this that mounting it on a wire rack works the best as seen here:
Edit (10/19/2014) Here is the same group of plants two months later without any direct human interaction. They grew from the light in the window and used up all of the water in the reservoir which was totally filled before I left.
To distribute the water to the plants, attach the vinyl tubing to the outflow of the pump and seal off the other end of the outflow tube. Run the tubing along the plants and drill holes wherever you’d like the water to exit.
You’ll also need to install the camera module in the Pi and point it wherever you’d like the frame of the photo to be.
The Software
As a preface, I’d like to at first say that this software was written entirely by me. I’ve never had any formal training in programming of any kind, so if there are obvious flaws with my code please let me know. That being said, I’ve found that this system is very effective and has worked for me and kept my plants alive for months.
All of this runs off of a base install of raspian on a raspberry pi model b.
There three major parts to the software. First, the prerequisites:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
apt-get install python-imaging python-imaging-tk python-pip mencoder python-dev git apache2 mysql-server php5 php5-mysql python-mysqldb python-serial php5-gd pip install tweepy apscheduler spidev wiringpi wget https://gdata-python-client.googlecode.com/files/gdata-2.0.18.tar.gz tar -xzvf gdata-2.0.18.tar.gz cd gdata-2.0.18/ sudo python setup.py install wget https://youtube-upload.googlecode.com/files/youtube-upload-0.7.2.tgz tar -xzvf youtube-upload-0.7.2.tgz cd youtube-upload-0.7.2/ sudo python setup.py install mkdir /srv/www/lib/ cd /srv/www/lib/ wget http://www.pchart.net/release/pChart2.1.3.tar.gz tar -xzvf pChart2.1.3.tar.gz mv pChart2.1.3 pChart |
You’ll need to enable SPI on your Pi in order to use the MCP3008 ADC. Do this by running the following commands:
1 |
sudo nano /etc/modprobe.d/raspi-blacklist.conf |
Comment out the spi-bcm2708 line so it looks like this:
1 |
#blacklist spi-bcm2708 |
Then run this to make it more permanent.
1 |
sudo modprobe spi-bcm2708 |
And finally reboot your Pi with:
1 |
sudo reboot |
Then the php code that renders the pChart graph. More details for installing pChart here and officially here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
<?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", "password"); //location of server, db username, db pass mysql_select_db("PiPlanter_DB", $db); $Requete = "SELECT * FROM PiPlanter_DB." .$argv[1]; $Result = mysql_query($Requete, $db); if (!$Result) { // add this check. die('Invalid query: ' . mysql_error()); } /*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"); $P_MST0 = $row["P_MST0"]; $myData->addPoints($P_MST0,"P_MST0"); $P_MST1 = $row["P_MST1"]; $myData->addPoints($P_MST1,"P_MST1"); $A_TMP0 = $row["A_TMP0"]; $myData->addPoints($A_TMP0,"A_TMP0"); $A_LDR0 = $row["A_LDR0"]; $myData->addPoints($A_LDR0,"A_LDR0"); } $myData-> setSerieOnAxis("P_MST0", 2); $myData-> setSerieOnAxis("P_MST1", 2); $myData-> setAxisName(2, "Relative Moisture [%]"); $myData-> setSerieOnAxis("A_TMP0", 0); //assigns the data to the first axis $myData-> setAxisName(0, "Degrees [F]"); //adds the label to the first axis $myData-> setSerieOnAxis("A_LDR0", 1); $myData-> setAxisName(1, "Ambient Light Level [%]"); $myData->setAbscissa("Time"); //sets the time data set as the x axis label $myData-> setSerieWeight("P_MST0",1); //draws the line thickness $myData->setPalette("P_MST0",array("R"=>58,"G"=>95,"B"=>205,"Alpha"=>80)); //sets the line color $myData-> setSerieWeight("P_MST1",1); $myData->setPalette("P_MST1",array("R"=>39,"G"=>64,"B"=>139,"Alpha"=>80)); $myData-> setSerieWeight("A_LDR0",2); $myData->setPalette("A_LDR0",array("R"=>255,"G"=>255,"B"=>0,"Alpha"=>80)); $myData-> setSerieTicks("A_LDR0", 4); $myData-> setSerieWeight("A_TMP0",2); $myData->setPalette("A_TMP0",array("R"=>255,"G"=>0,"B"=>0,"Alpha"=>80)); $myData-> setSerieTicks("A_TMP0", 4); // $myPicture = new pImage(1000,700,$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(210,40,900,600); /* Define the boundaries of the graph area */ // $myPicture->drawScale(array("LabelRotation"=>320)); /* Draw the scale, keep everything automatic */ $myPicture = new pImage(1300,700,$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(210,40,1200,600); /* 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,"LabelRotation"=>320)); $myPicture->drawLineChart(); $myPicture->drawLegend(30,30); //adds the legend $time = date("d-M-Y_H:i:s"); $myPicture->render($argv[2].$time.".png"); print($argv[2].$time.".png"); |
And now the star of the show, the python script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 |
import MySQLdb from datetime import datetime import time from time import sleep import os import sys import spidev import RPi.GPIO as GPIO import logging logging.basicConfig() from apscheduler.schedulers.blocking import BlockingScheduler import subprocess def ConsoleDebug(input): debug = '[' + datetime.now().strftime("%m-%d-%Y_%I-%M-%S-%p") + '] Debug: ' + input print debug file = open(str(os.getcwd()) + "/log.txt", "a") file.write(debug + "\n") file.close() def FirstTimeSetup(): global cycle ConsoleDebug('---------------- NEW INSTANCE OF PIPLANTER ----------------') MySQL_Commands = {1 : 'CREATE DATABASE IF NOT EXISTS PiPlanter_DB', 2: "GRANT ALL ON `PiPlanter_DB`.* TO 'piplanter'@'localhost' IDENTIFIED BY 'password'", 3: 'USE PiPlanter_DB' } for i in MySQL_Commands.itervalues(): ConsoleDebug('MYSQL COMMAND: ' + i) cursor.execute(i) MySQLTableSetup(False,'Daily',True) VisualLocationSetup(True,'dontcare') ConsoleDebug('Setup Complete') cycle = 0 def MySQLTableSetup(full,kind,first): global MySQL_Tables now = datetime.now().strftime("%m_%d_%Y__%I_%M_%S%p") if first == True: MySQL_Tables = { 'MySQLTable_Daily' : 'DailyTable' + now, 'MySQLTable_Weekly' : 'WeeklyTable' + now, 'MySQLTable_Monthly' : 'MonthlyTable' + now} if full == False: CreateTables = {0: "CREATE TABLE " + MySQL_Tables['MySQLTable_Daily'] + "(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))", 1 : "CREATE TABLE " + MySQL_Tables['MySQLTable_Weekly'] + "(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))" , 2 : "CREATE TABLE " + MySQL_Tables['MySQLTable_Monthly'] + "(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))"} for i in CreateTables.itervalues(): ConsoleDebug('MYSQL COMMAND: ' + i) cursor.execute(i) if full == True: CreateTables = {0: "CREATE TABLE " + MySQL_Tables['MySQLTable_Daily'] + "(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))", 1:"CREATE TABLE " + MySQL_Tables['MySQLTable_Weekly'] + "(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))" , 2:"CREATE TABLE " + MySQL_Tables['MySQLTable_Monthly'] + "(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))" } for i in CreateTables.itervalues(): ConsoleDebug('MYSQL COMMAND: ' + i) cursor.execute(i) elif first == False: if kind == 'Daily': ConsoleDebug('Daily Database Name Has Been Updated') MySQL_Tables['MySQLTable_Daily'] = 'DailyTable_' + now ConsoleDebug(MySQL_Tables['MySQLTable_Daily']) if full == False: CreateTable = "CREATE TABLE " + MySQL_Tables['MySQLTable_Daily'] + "(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))" elif full == True: CreateTable = "CREATE TABLE " + MySQL_Tables['MySQLTable_Daily'] + "(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))" elif kind == 'Weekly': ConsoleDebug('Daily Database Name Has Been Updated') MySQL_Tables['MySQLTable_Weekly'] = 'WeeklyTable_' + now ConsoleDebug(MySQL_Tables['MySQLTable_Weekly']) if full == False: CreateTable = "CREATE TABLE " + MySQL_Tables['MySQLTable_Weekly'] + "(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))" elif full == True: CreateTable = "CREATE TABLE " + MySQL_Tables['MySQLTable_Weekly'] + "(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))" elif kind == 'Monthly': ConsoleDebug('Daily Database Name Has Been Updated') MySQL_Tables['MySQLTable_Monthly'] = 'MonthlyTable_' + now ConsoleDebug(MySQL_Tables['MySQLTable_Monthly']) if full == False: CreateTable = "CREATE TABLE " + MySQL_Tables['MySQLTable_Monthly'] + "(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))" elif full == True: CreateTable = "CREATE TABLE " + MySQL_Tables['MySQLTable_Monthly'] + "(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))" ConsoleDebug('MYSQL: ' + CreateTable) cursor.execute(CreateTable) ConsoleDebug('Current Daily: ' + MySQL_Tables['MySQLTable_Daily']) ConsoleDebug('Current Weekly: ' + MySQL_Tables['MySQLTable_Weekly']) ConsoleDebug('Current Monthly: ' + MySQL_Tables['MySQLTable_Monthly']) def VisualLocationSetup(first,kind): global VisualLocation now = datetime.now().strftime("%m_%d_%Y__%I_%M_%S%p") runninglocation = str(os.getcwd()) if first == True: ConsoleDebug('Creating Video Directory') if not os.path.exists(runninglocation + '/videos/'): os.makedirs(runninglocation + '/videos/') ConsoleDebug('Video Directory Created') else: ConsoleDebug('Video Directory Already Exists') ConsoleDebug('Creating Daily Video Directory') if not os.path.exists(runninglocation + '/videos/dailys/'): os.makedirs(runninglocation + '/videos/dailys/') else: ConsoleDebug('Daily Video Directory Already Exists') ConsoleDebug('Creating Image Directory') if not os.path.exists(runninglocation + '/images/'): os.makedirs(runninglocation + '/images/') else: ConsoleDebug('Image Directory Already Exists') ConsoleDebug('Creating Daily Image Directory') if not os.path.exists(runninglocation + '/images/dailys/'): os.makedirs(runninglocation + '/images/dailys/') else: ConsoleDebug('Daily Image Directory Already Exists') ConsoleDebug('Creating Graph Directory') if not os.path.exists(runninglocation + '/graphs/'): os.makedirs(runninglocation + '/graphs/') else: ConsoleDebug('Graph Directory Already Exists') ConsoleDebug('Updating All Current Visual Directories') VisualLocation = {'CurrentImageDirectory' : runninglocation + '/images/dailys/' + 'CurrentImageDirectory_' + now + '/' , 'CurrentVideoDirectory' : runninglocation + '/videos/dailys/' + 'CurrentVideoDirectory_' + now + '/' , 'CurrentGraphDirectory' : runninglocation + '/graphs/' + 'CurrentGraphDirectory_' + now + '/' } for i in VisualLocation.itervalues(): ConsoleDebug('Making Directory: ' + i) os.makedirs(i) if first == False: ConsoleDebug('Updating Location Of ' + kind + ' Directory') if kind == 'Image': VisualLocation['CurrentImageDirectory'] = runninglocation + '/images/dailys/' + 'CurrentImageDirectory_' + now + '/' ConsoleDebug('Making Directory: ' + VisualLocation['CurrentImageDirectory']) os.makedirs(VisualLocation['CurrentImageDirectory']) elif kind == 'Video': VisualLocation['CurrentVideoDirectory'] = runninglocation + '/videos/dailys/' + 'CurrentVideoDirectory_' + now + '/' ConsoleDebug('Making Directory: ' + VisualLocation['CurrentVideoDirectory']) os.makedirs(VisualLocation['CurrentVideoDirectory']) elif kind == 'Graph': VisualLocation['CurrentGraphDirectory'] = runninglocation + '/graphs/' + 'CurrentGraphDirectory_' + now + '/' ConsoleDebug('Making Directory: ' + VisualLocation['CurrentGraphDirectory']) os.makedirs(VisualLocation['CurrentGraphDirectory']) ConsoleDebug('Current Image Directory' + VisualLocation['CurrentImageDirectory']) ConsoleDebug('Current Video Directory' + VisualLocation['CurrentVideoDirectory']) ConsoleDebug('Current Graph Directory' + VisualLocation['CurrentGraphDirectory']) return 0 #this function can be used to find out the ADC value on ADC 0 def ReadADC0(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 ReadADC1(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 return 0 #returns a usable numerical value from the ADC def PollSensor(sensor,unit,precision,samples): GPIO.output(pins['MST_Enable'], True) if PiPlanterFull == True: #Full PiPlanter sensors = {\ 'P_TMP0' : ConvertADC(ReadADC0(0),unit),\ 'P_MST0' : ConvertADC(ReadADC0(1),unit),\ 'P_TMP1' : ConvertADC(ReadADC0(2),unit),\ 'P_MST1' : ConvertADC(ReadADC0(3),unit),\ 'P_TMP2' : ConvertADC(ReadADC0(4),unit),\ 'P_MST2' : ConvertADC(ReadADC0(5),unit),\ 'P_TMP3' : ConvertADC(ReadADC0(6),unit),\ 'P_MST3' : ConvertADC(ReadADC0(7),unit),\ 'A_TMP0' : ConvertADC(ReadADC1(0),unit),\ 'A_LDR0' : ConvertADC(ReadADC1(1),unit),\ 'A_LDR1' : ConvertADC(ReadADC1(2),unit),\ 'A_MST0' : ConvertADC(ReadADC1(3),unit)} else: #Simple PiPlanter sensors = {\ 'P_MST0' : ConvertADC(ReadADC0(0),unit),\ 'P_MST1' : ConvertADC(ReadADC0(1),unit),\ 'A_TMP0' : ConvertADC(ReadADC0(2),unit),\ 'A_LDR0' : ConvertADC(ReadADC0(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,Full): global MySQL_Tables if 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 Full == True: #Full PiPlanter cursor.execute("INSERT INTO " + MySQL_Tables['MySQLTable_Daily'] + "(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']) + ")" ) user.commit() cursor.execute("INSERT INTO " + MySQL_Tables['MySQLTable_Weekly'] + "(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']) + ")" ) user.commit() cursor.execute("INSERT INTO " + MySQL_Tables['MySQLTable_Monthly'] + "(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']) + ")" ) user.commit() ConsoleDebug('MySQL Tables Updated Full') output = "INSERT INTO " + MySQL_Tables['MySQLTable_Monthly'] + "(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 cursor.execute("INSERT INTO " + MySQL_Tables['MySQLTable_Daily'] + "(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']) + ")" ) user.commit() cursor.execute("INSERT INTO " + MySQL_Tables['MySQLTable_Weekly'] + "(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']) + ")" ) user.commit() cursor.execute("INSERT INTO " + MySQL_Tables['MySQLTable_Monthly'] + "(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']) + ")" ) user.commit() ConsoleDebug('MySQL Tables Updated Simple') output = "INSERT INTO " + MySQL_Tables['MySQLTable_Daily'] + "(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 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 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 a given amount of water from a given pump def PumpWater(pump,volume): LPM = 4.00 #L per minute ontime = volume*(60/LPM) ConsoleDebug('PUMP ON') GPIO.output(pumps[pump],True) time.sleep(ontime) GPIO.output(pumps[pump],False) ConsoleDebug('PUMP OFF') output = 'Pumped ' + str(volume) + ' L Of Water Into Plants In ' + str(ontime) + ' Seconds' ConsoleDebug(output) return output def Image(dir,cycle,high_quality): image = dir + str(cycle).zfill(4) + '.jpg' if high_quality == False: picture_command = 'raspistill -q 10 -o ' + image if high_quality == True: picture_command = 'raspistill -q 100 -o ' + image os.system(picture_command) ConsoleDebug('Image Captured, High Quality = ' + str(high_quality) + ', Image: ' + str(image)) return image def RenderGraph(table,location): ConsoleDebug('Rendering Graph') rendercommand = 'php ' + str(os.getcwd()) + '/pChartRender_1_0_5.php ' + table + ' ' + location ConsoleDebug('Running Command: ' + rendercommand) proc = subprocess.Popen(rendercommand, shell=True, stdout=subprocess.PIPE) script_response = proc.stdout.read() ConsoleDebug('Output File: ' + script_response) ConsoleDebug('Rendering Complete') return script_response def TryTweet(image, imagelocation, text): for i in range(10): try: 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) ConsoleDebug('Attempt [' + str(i) + '] To Tweet: ' + text + ' , image = ' + str(image)) if image == True: output = api.update_with_media(imagelocation, text) if image == False: output = api.update_status(text) break except tweepy.error.TweepError as e: ConsoleDebug('Tweet Failed, Retrying') ConsoleDebug('Twitter Error: ' + str(e)) i = i + 1 time.sleep(15) if i < 10: ConsoleDebug('Tweet Sent After ' + str(i) + ' Attempts, Details: Actual Text [ ' + str(output.text) + '] URL: https://twitter.com/piplanter_bot/status/' + str(output.id) ) if i == 10: ConsoleDebug('Tweet Was a Failure') def RenderVideo(infolder,outfolder): outputfile = outfolder + str(datetime.now().strftime("%m_%d_%Y__%I_%M_%S%p")) + '_VIDEO.avi' ConsoleDebug('Attempting To Render: ' + outputfile) render_command = 'sudo mencoder mf://' + str(infolder) + '*.jpg -nosound -ovc lavc -lavcopts vcodec=mpeg4:aspect=16/9:vbitrate=8000000 -vf scale=1920:1080 -mf type=jpeg:fps=15 -o ' + outputfile os.system(render_command) ConsoleDebug('Render Complete, File: ' + outputfile) return outputfile def UploadVideo(video,email,password): humantime = str(datetime.now().strftime("%m/%d/%Y")) title = 'Time Lapse of Tomato Plants of the Three Days Prior To ' + str(humantime) description = 'Confused? https://esologic.com/?page_id=1042' category = 'Tech' keywords = 'piplanter' uploadcommand = 'youtube-upload --email=' + email + ' --password=' + password + ' --title="' + title +'"'+ ' --description="' + description + '"' + ' --category=' + category + ' --keywords=' + keywords + ' ' + os.path.normpath(video) ConsoleDebug('Upload Command: ' + uploadcommand) for i in range(10): try: ConsoleDebug('Attempt [' + str(i) + '] To Upload: ' + str(video)) proc = subprocess.Popen(uploadcommand, shell=True, stdout=subprocess.PIPE) output = proc.stdout.read() break except: ConsoleDebug('Upload Failed, Retrying') ConsoleDebug('Upload Error: ' + str(output)) i = i + 1 time.sleep(15) if i < 10: ConsoleDebug('Uploaded After ' + str(i) + ' Attempts, Details: URL [ ' + str(output) + ']' ) return output if i == 10: ConsoleDebug('Upload Was a Failure') return 'Upload was a Failure' def TwentyMinutes(): global cycle SampleAllSensors(1,1000,'MySQL',False) ConsoleDebug(SampleAllSensors(5,1000,'Console',False)) image = Image(VisualLocation['CurrentImageDirectory'],cycle,False) tweet = SampleAllSensors(3,20,'Twitter',False) + " https://esologic.com/?page_id=1042" tweet = tweet = SampleAllSensors(3,20,'Twitter',False) + " https://esologic.com/?page_id=1042" TryTweet(True,image,tweet) cycle = cycle + 1 def ThreeHours(): graphlocation = RenderGraph(MySQL_Tables['MySQLTable_Daily'],VisualLocation['CurrentGraphDirectory']) tweet = 'Graph of day so far: Moisture % - Blue, Ambient Light % - Yellow, Temp DF - Red https://esologic.com/?page_id=1042' TryTweet(True,graphlocation,tweet) ConsoleDebug('ThreeHours Complete') def Daily(): graphlocation = RenderGraph(MySQL_Tables['MySQLTable_Daily'],VisualLocation['CurrentGraphDirectory']) MySQLTableSetup(False,'Daily',False) tweet = 'Graph of Previous 24 Hours: Moisture % - Blue, Ambient Light % - Yellow, Temp DF - Red https://esologic.com/?page_id=1042' TryTweet(True,graphlocation,tweet) tweet2 = PumpWater('PUMP0',2.5) TryTweet(False,'',tweet2) ConsoleDebug('Daily Complete') def ThreeDays(): graphlocation = RenderGraph(MySQL_Tables['MySQLTable_Weekly'],VisualLocation['CurrentGraphDirectory']) video = RenderVideo(VisualLocation['CurrentImageDirectory'],VisualLocation['CurrentVideoDirectory']) yt_url = UploadVideo(video,"YOUREMAIL@gmail.com","YOURPASSWORD") tweet1 = 'Graph of Week So Far: Moisture % - Blue, Ambient Light % - Yellow, Temp DF - Red https://esologic.com/?page_id=1042' tweet2 = 'Time Lapse Video of Previous Three Days: ' + yt_url TryTweet(True,graphlocation,tweet1) TryTweet(False,'',tweet2) VisualLocationSetup(False,'Image') VisualLocationSetup(False,'Video') ConsoleDebug('ThreeDays Complete') def Weekly(): graphlocation = RenderGraph(MySQL_Tables['MySQLTable_Weekly'],VisualLocation['CurrentGraphDirectory']) tweet = 'Graph of Previous Week: Moisture % - Blue, Ambient Light % - Yellow, Temp DF - Red https://esologic.com/?page_id=1042' TryTweet(True,graphlocation,tweet) MySQLTableSetup(False,'Weekly',False) ConsoleDebug('Weekly Complete') if __name__ == '__main__': global MySQL_Tables global VisualLocation GPIO.setmode(GPIO.BOARD) pins = {'MST_Enable' : 8} #assign names to GPIO pins for d in pins.itervalues(): GPIO.setup(d,GPIO.OUT) pumps = {'PUMP0' : 7, 'PUMP1' : 11, 'PUMP2' : 13, 'PUMP3' : 16} #assign names to GPIO pins for k in pumps.itervalues(): GPIO.setup(k,GPIO.OUT) #first ADC setup on SPI port 1 spi_1 = spidev.SpiDev() spi_1.open(0, 1) #first ADC setup on SPI port 0 spi_0 = spidev.SpiDev() spi_0.open(0, 0) PiPlanterFull = False user = MySQLdb.connect(host="localhost",user="root",passwd="YOURMYSQL PASSWORD") cursor = user.cursor() scheduler = BlockingScheduler() scheduler.add_job(TwentyMinutes, 'interval', minutes = 20) scheduler.add_job(ThreeHours,'interval', hours = 3) scheduler.add_job(Daily,'interval', days=1) scheduler.add_job(ThreeDays,'interval', days = 3) scheduler.add_job(Weekly,'interval', weeks=1) try: FirstTimeSetup() scheduler.start() except (KeyboardInterrupt, SystemExit): pass |
Before running, make sure you make the following changes to the script:
You’ll need set up access to twitter API’s, seen here. You’ll need to input your information about your twitter app into into 331-334 of this script.
You’ll need to input information about your YouTube account on line 429
On line 473 you’ll need to input your mysql information.
Output Demos
The PiPlanter is very connected. It renders graphs of data, takes images and renders timelapse videos.
Here’s a standard tweet showing the plants:
Ambient Light: 86.6%, Ambient Temp: 66.1DF, Average Plant Mst: 90.9% http://t.co/U75XO1EUvG pic.twitter.com/gtj2VeoFOT
— piplanter_bot (@piplanter_bot) September 11, 2014
Here’s a tweet showing a day’s worth of data in a graph render:
Graph of day so far: Moisture % – Blue, Ambient Light % – Yellow, Temp DF – Red http://t.co/U75XO1EUvG pic.twitter.com/fEbnicWN2j — piplanter_bot (@piplanter_bot) September 11, 2014
Here’s a tweet showing a week’s worth of data in a graph render:
Graph of Previous Week: Moisture % – Blue, Ambient Light % – Yellow, Temp DF – Red http://t.co/U75XO1EUvG pic.twitter.com/oGAHyh9vB1
— piplanter_bot (@piplanter_bot) September 11, 2014
Here’s a timelapse video of three days:
Follow @PiPlanter_Bot for updates on my plants.
That’s pretty much it! Please feel free to modify this code for any use you’d like.
All of my research on this project can be found here.
Thanks for reading, and please leave a comment if you like my work!