{"id":85,"date":"2013-10-15T16:08:05","date_gmt":"2013-10-15T16:08:05","guid":{"rendered":"http:\/\/blog.cup-of-joe.me\/?p=85"},"modified":"2013-10-15T16:08:05","modified_gmt":"2013-10-15T16:08:05","slug":"python-code","status":"publish","type":"post","link":"http:\/\/blog.cup-of-joe.me\/?p=85","title":{"rendered":"Python Code"},"content":{"rendered":"<p>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 &#8220;clean&#8221;.  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&#8217;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&#8217;m not worried about size, speed, or cleanliness;  just that it works.  \ud83d\ude42  If you are going to use this, be aware of 3 things:<br \/>\n1. You&#8217;ll need to sign up for your own API from Weather Underground.<br \/>\n2. You&#8217;ll need make sure you&#8217;ve installed all the necessary libraries on your Pi.  (Read Adafruit&#8217;s reading analog data tutorial for this piece.  I&#8217;ll try to put something together in order to show all of the steps necessary to get this to work.)<br \/>\n3. You&#8217;ll need to change your MySQL connection variables<\/p>\n<p>So without further adieu:<\/p>\n<p><code><\/p>\n<p>#!\/usr\/bin\/env python<br \/>\nimport time<br \/>\nimport os<br \/>\nimport RPi.GPIO as GPIO<br \/>\nimport MySQLdb<br \/>\nimport urllib2<\/p>\n<p>#set up some GPIO settings<br \/>\nGPIO.setmode(GPIO.BCM)<br \/>\nGPIO.setwarnings(False)<\/p>\n<p># set up pin that provides power to moisture probes<br \/>\nGPIO.setup(17, GPIO.OUT)<br \/>\nGPIO.output(17, True)<\/p>\n<p>#read inside temperature sensor.  temperature = temp in degrees C<br \/>\ntfile = open(\"\/sys\/bus\/w1\/devices\/28-000004d608e1\/w1_slave\")<br \/>\ntext = tfile.read()<br \/>\ntfile.close()<br \/>\ntemperaturedata = text.split(\"\\n\")[1].split(\" \")[9]<br \/>\ntemperature = float(temperaturedata[2:])<br \/>\ntemperature = temperature \/ 1000<\/p>\n<p>#go get outside humidity from weather underground using api<br \/>\n#reading json file to line that contains humidity and pulling<br \/>\n#out the numbers in the text<br \/>\nreq = urllib2.Request('http:\/\/api.wunderground.com\/api\/****************\/conditions\/q\/TX\/Forney.json')<br \/>\nresponse = urllib2.urlopen(req)<\/p>\n<p>read_until = 52<br \/>\nhumid_line = 54<\/p>\n<p>correctline = []<br \/>\ncorrect_humid_line = []<br \/>\nlines = []<\/p>\n<p>for line_number, line in enumerate(response.readlines()):<br \/>\n    if line_number == read_until:<br \/>\n        correctline.append(line)<br \/>\n    elif line_number == humid_line:<br \/>\n        correct_humid_line.append(line)<br \/>\n    else:<br \/>\n        lines.append(line)<\/p>\n<p>pull_humid = ','.join(correct_humid_line)<\/p>\n<p>out_humid = pull_humid[-6:-4]<br \/>\nout_humid = round(float(out_humid),1)<\/p>\n<p># convert celsius to fahrenheit for inside temp<br \/>\ntemp_F = ( temperature * 9.0 \/ 5.0 ) + 32<\/p>\n<p># show only one decimal place for temperature<br \/>\ntemp_F = \"%.1f\" % temp_F<br \/>\ntemp_C = temperature<\/p>\n<p># read SPI data from MCP3008 chip, 8 possible adc's (0 thru 7)<br \/>\ndef readadc(adcnum, clockpin, mosipin, misopin, cspin):<br \/>\n        if ((adcnum > 7) or (adcnum < 0)):\n                return -1\n        GPIO.output(cspin, True)\n\n        GPIO.output(clockpin, False)  # start clock low\n        GPIO.output(cspin, False)     # bring CS low\n\n        commandout = adcnum\n        commandout |= 0x18  # start bit + single-ended bit\n        commandout <<= 3    # we only need to send 5 bits here\n        for i in range(5):\n                if (commandout &#038; 0x80):\n                        GPIO.output(mosipin, True)\n                else:   \n                        GPIO.output(mosipin, False)\n                commandout <<= 1\n                GPIO.output(clockpin, True)\n                GPIO.output(clockpin, False)\n\n        adcout = 0\n        # read in one empty bit, one null bit and 10 ADC bits\n        for i in range(12):\n                GPIO.output(clockpin, True)\n                GPIO.output(clockpin, False)\n                adcout <<= 1\n                if (GPIO.input(misopin)):\n                        adcout |= 0x1\n\n        GPIO.output(cspin, True)\n\n        adcout \/= 2       # first bit is 'null' so drop it\n        return adcout\n\n# change these as desired - they're the pins connected from the\n# SPI port on the ADC to the Cobbler.  Since I am using 2 ADCs\n#I have 2 chip select pins.  25 for the first one and 8 for the\n#second one\nSPICLK = 18\nSPIMISO = 23\nSPIMOSI = 24\nSPICS = 25\nSPICS1 = 8\n\n# set up the SPI interface pins\nGPIO.setup(SPIMOSI, GPIO.OUT)\nGPIO.setup(SPIMISO, GPIO.IN)\nGPIO.setup(SPICLK, GPIO.OUT)\nGPIO.setup(SPICS, GPIO.OUT)\nGPIO.setup(SPICS1, GPIO.OUT)\n\n# set up the pin locations of the different probes.  Can only be\n#0-7 as there are only 8 pins per ADC\nreadadc0 = 0\nreadadc2 = 2\nreadadc3 = 3\nreadadc4 = 4\nreadadc5 = 5\nreadadc6 = 6\nreadadc7 = 7\nreadadc8 = 0\nreadadc9 = 1\nreadadc10 = 2\nreadadc11 = 3\nreadadc12 = 4\nreadadc13 = 5\nreadadc15 = 7\n\n\n# read the analog pins.  Assigning reads to sensor variables\nlux_sens0 = readadc(readadc0, SPICLK, SPIMOSI, SPIMISO, SPICS)\nmoisture_sens1 = readadc(readadc2, SPICLK, SPIMOSI, SPIMISO, SPICS)\nlux_sens1 = readadc(readadc3, SPICLK, SPIMOSI, SPIMISO, SPICS)\nmoisture_sens2 = readadc(readadc4, SPICLK, SPIMOSI, SPIMISO, SPICS)\nlux_sens2 = readadc(readadc5, SPICLK, SPIMOSI, SPIMISO, SPICS)\nmoisture_sens3 = readadc(readadc6, SPICLK, SPIMOSI, SPIMISO, SPICS)\nlux_sens3 = readadc(readadc7, SPICLK, SPIMOSI, SPIMISO, SPICS)\nmoisture_sens4 = readadc(readadc8, SPICLK, SPIMOSI, SPIMISO, SPICS1)\nlux_sens4 = readadc(readadc9, SPICLK, SPIMOSI, SPIMISO, SPICS1)\nmoisture_sens5 = readadc(readadc10, SPICLK, SPIMOSI, SPIMISO, SPICS1)\nlux_sens5 = readadc(readadc11, SPICLK, SPIMOSI, SPIMISO, SPICS1)\nmoisture_sens6 = readadc(readadc12, SPICLK, SPIMOSI, SPIMISO, SPICS1)\nlux_sens6 = readadc(readadc13, SPICLK, SPIMOSI, SPIMISO, SPICS1)\nhumid_sens = readadc(readadc15, SPICLK, SPIMOSI, SPIMISO, SPICS1)\n\n\n# convert reading from humidity sensor to humidity based on formula\n# from datasheet\nsensor_humid = (((humid_sens*3.3\/1023\/3.3)-.1515)\/.00636)\nhumid = sensor_humid \/(1.0546 - .00216 * float(temp_C))\ninhumid = round(humid,1)\n\n# convert lux into relative terms\n\n#lux0\nif lux_sens0 < 10:\n\tlux0 = \"Dark\"\nelif lux_sens0 < 200:\n\tlux0 = \"Dim\"\nelif lux_sens0 < 500:\n\tlux0 = \"Light\"\nelif lux_sens0 < 800:\n\tlux0 = \"Bright\"\nelse:\n\tlux0 = \"Very Bright\"\n\n#lux1\nif lux_sens1 < 10:\n        lux1 = \"Dark\"\nelif lux_sens1 < 200:\n        lux1 = \"Dim\"\nelif lux_sens1 < 500:\n        lux1 = \"Light\"\nelif lux_sens1 < 800:\n        lux1 = \"Bright\"\nelse:\n        lux1 = \"Very Bright\"\n\n#lux2\nif lux_sens2 < 10:\n        lux2 = \"Dark\"\nelif lux_sens2 < 200:\n        lux2 = \"Dim\"\nelif lux_sens2 < 500:\n        lux2 = \"Light\"\nelif lux_sens2 < 800:\n        lux2 = \"Bright\"\nelse:\n        lux2 = \"Very Bright\"\n\n#lux3\nif lux_sens3 < 10:\n        lux3 = \"Dark\"\nelif lux_sens3 < 200:\n        lux3 = \"Dim\"\nelif lux_sens3 < 500:\n        lux3 = \"Light\"\nelif lux_sens3 < 800:\n        lux3 = \"Bright\"\nelse:\n        lux3 = \"Very Bright\"\n\n#lux4\nif lux_sens4 < 10:\n        lux4 = \"Dark\"\nelif lux_sens4 < 200:\n        lux4 = \"Dim\"\nelif lux_sens4 < 500:\n        lux4 = \"Light\"\nelif lux_sens4 < 800:\n        lux4 = \"Bright\"\nelse:\n        lux4 = \"Very Bright\"\n\n#lux5\nif lux_sens5 < 10:\n        lux5 = \"Dark\"\nelif lux_sens5 < 200:\n        lux5 = \"Dim\"\nelif lux_sens5 < 500:\n        lux5 = \"Light\"\nelif lux_sens5 < 800:\n        lux5 = \"Bright\"\nelse:\n        lux5 = \"Very Bright\"\n\n#lux6\nif lux_sens6 < 10:\n        lux6 = \"Dark\"\nelif lux_sens6 < 200:\n        lux6 = \"Dim\"\nelif lux_sens6 < 500:\n        lux6 = \"Light\"\nelif lux_sens6 < 800:\n        lux6 = \"Bright\"\nelse:\n        lux6 = \"Very Bright\"\n\n# convert moisture into relative terms\n\n\n# moisture1\nif moisture_sens1 < 150:\n\tmoisture1 = \"Dry\"\nelif moisture_sens1 < 350:\n\tmoisture1 = \"Moist\"\nelse:\n\tmoisture1 = \"Wet\"\n\n# moisture2\nif moisture_sens2 < 150:\n        moisture2 = \"Dry\"\nelif moisture_sens2 < 350:\n        moisture2 = \"Moist\"\nelse:\n        moisture2 = \"Wet\"\n\n# moisture3\nif moisture_sens3 < 150:\n        moisture3 = \"Dry\"\nelif moisture_sens3 < 350:\n        moisture3 = \"Moist\"\nelse:\n        moisture3 = \"Wet\"\n\n# moisture4\nif moisture_sens4 < 150:\n        moisture4 = \"Dry\"\nelif moisture_sens4 < 350:\n        moisture4 = \"Moist\"\nelse:\n        moisture4 = \"Wet\"\n\n# moisture5\nif moisture_sens5 < 150:\n        moisture5 = \"Dry\"\nelif moisture_sens5 < 350:\n        moisture5 = \"Moist\"\nelse:\n        moisture5 = \"Wet\"\n\n# moisture6\nif moisture_sens6 < 150:\n        moisture6 = \"Dry\"\nelif moisture_sens6 < 350:\n        moisture6 = \"Moist\"\nelse:\n        moisture6 = \"Wet\"\n        \n        \n# get temp from outside sensor.  Needed to do this down lower\n# as to not get readings from sensors confused\n# they are attached to the same pin\ntfile1 = open(\"\/sys\/bus\/w1\/devices\/28-000004cfffc6\/w1_slave\")\ntext1 = tfile1.read()\ntfile1.close()\ntemperaturedata1 = text1.split(\"\\n\")[1].split(\" \")[9]\ntemperature1 = float(temperaturedata1[2:])\ntemperature1 = temperature1 \/ 1000\n\ntemp_F1 = ( temperature1 * 9.0 \/ 5.0 ) + 32\ntemp_F1 = \"%.1f\" % temp_F1\n\n#set in and out temps to variables I can understand\nin_temp = temp_F\nout_temp = temp_F1\n\n#printing out the readings.  Not needed, but used for testing purposes\nprint(\"temp_F:\", temp_F)\nprint(\"temp_F1:\", temp_F1)\nprint(\"lux0:\", lux0)\nprint(\"moisture1:\", moisture1)\nprint(\"lux1\", lux1)\nprint(\"moisture2:\", moisture2)\nprint(\"lux2\", lux2)\nprint(\"moisture3:\", moisture3)\nprint(\"lux3\", lux3)\nprint(\"moisture4:\", moisture4)\nprint(\"lux4\", lux4)\nprint(\"moisture5:\", moisture5)\nprint(\"lux5\", lux5)\nprint(\"moisture6:\", moisture6)\nprint(\"lux6\", lux6)\nprint(\"Inside humid:\", round(inhumid,1), \"%\")\nprint(\"Outside humid:\", round(float(out_humid),1), \"%\")\nprint(\"moisture_sens1:\", moisture_sens1)\nprint(\"moisture_sens2:\", moisture_sens2)\nprint(\"moisture_sens3:\", moisture_sens3)\nprint(\"moisture_sens4:\", moisture_sens4)\nprint(\"moisture_sens5:\", moisture_sens5)\nprint(\"moisture_sens6:\", moisture_sens6)\n\n\n\n#setting the pin that provides the power to the moisture sensors \n# to an input as to not provide power in between readings\nGPIO.output(17, False)\nGPIO.cleanup()\n\n\n#setting up pin for heater switch\npower_pin = 22\n\nGPIO.setup(power_pin, GPIO.OUT)\nGPIO.setup(power_pin, False)\n\n\n# if temperature is below a certain point, turn the heater on\nif float(temp_F1) < 50:\n        GPIO.output(power_pin, True)\n        htr_status = \"ON\"\nelse:\n        GPIO.output(power_pin, False)\n        htr_status = \"OFF\"\n\nprint(\"heater\", htr_status)\n\n\n#setting up pin for pump switch\npump_pin = 11\n\nGPIO.setup(pump_pin, GPIO.OUT)\nGPIO.setup(pump_pin, False)\n\n\n#check to see how many moisture sensors are reading as \"Dry\"\nmoisture_count = 0\n\nif moisture1 == \"Dry\":\n\tmoisture_count = moisture_count + 1\n\nif moisture2 == \"Dry\":\n        moisture_count = moisture_count + 1\n\nif moisture3 == \"Dry\":\n        moisture_count = moisture_count + 1\n\nif moisture4 == \"Dry\":\n        moisture_count = moisture_count + 1\n\nif moisture5 == \"Dry\":\n        moisture_count = moisture_count + 1\n\nif moisture6 == \"Dry\":\n        moisture_count = moisture_count + 1\n\n# if more than a certain amount of sensor read \"Dry\", then turn on the pump\nif float(moisture_count) > 1:<br \/>\n        GPIO.output(pump_pin, True)<br \/>\n        pump_status = \"ON\"<br \/>\nelse:<br \/>\n        GPIO.output(pump_pin, False)<br \/>\n        pump_status = \"OFF\"<\/p>\n<p>print(\"pump status:\", pump_status)<\/p>\n<p># alarm setup if pump is not coming on.  (Will use this later when I<br \/>\n# add the float sensor to the rain barrel to make sure the pump<br \/>\n# doesn't come on when there's no water.)  This will act as my alarm<br \/>\n# if there is no water in the barrel<br \/>\nif moisture_count > 3 and pump_status == \"OFF\":<br \/>\n\tmoisture_alarm = \"ON\"<br \/>\nelse:<br \/>\n\tmoisture_alarm = \"OFF\"<\/p>\n<p># Placing data into the database<\/p>\n<p># Open database connection<br \/>\ndb = MySQLdb.connect(host=\"IP Address\", port=3306, user= \"user_name\", passwd=\"Password\" )<\/p>\n<p># prepare a cursor object using cursor() method<br \/>\ncursor = db.cursor()<\/p>\n<p># Prepare SQL query to INSERT a record into the database.<br \/>\nsql = \"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) + \"')\"<br \/>\nprint(\"sql:\", sql)<br \/>\n#try:<br \/>\n # Execute the SQL command<br \/>\ncursor.execute(sql)<br \/>\n   # Fetch all the rows in a list of lists.<br \/>\n#except:<br \/>\n#   print \"Error: Unable to Insert Data\"<\/p>\n<p># disconnect from server<br \/>\ndb.close()<\/p>\n<p><\/code><\/p>\n<p>Such a marvelous little computer&#8230;<\/p>\n<p><a href=\"http:\/\/blog.cup-of-joe.me\/wp-content\/uploads\/2013\/10\/20131015-110724.jpg\"><img decoding=\"async\" src=\"http:\/\/blog.cup-of-joe.me\/wp-content\/uploads\/2013\/10\/20131015-110724.jpg\" alt=\"20131015-110724.jpg\" class=\"alignnone size-full\" \/><\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>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 &#8220;clean&#8221;. It is just me throwing some stuff down to get it to work. I am not really an OO guy; I think procedurally and [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[3],"tags":[],"_links":{"self":[{"href":"http:\/\/blog.cup-of-joe.me\/index.php?rest_route=\/wp\/v2\/posts\/85"}],"collection":[{"href":"http:\/\/blog.cup-of-joe.me\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/blog.cup-of-joe.me\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/blog.cup-of-joe.me\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/blog.cup-of-joe.me\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=85"}],"version-history":[{"count":1,"href":"http:\/\/blog.cup-of-joe.me\/index.php?rest_route=\/wp\/v2\/posts\/85\/revisions"}],"predecessor-version":[{"id":86,"href":"http:\/\/blog.cup-of-joe.me\/index.php?rest_route=\/wp\/v2\/posts\/85\/revisions\/86"}],"wp:attachment":[{"href":"http:\/\/blog.cup-of-joe.me\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=85"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/blog.cup-of-joe.me\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=85"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/blog.cup-of-joe.me\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=85"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}