Created
May 14, 2016 16:13
-
-
Save donotknowspoon/3de5e31cb91c6d1f38dd029b860689b5 to your computer and use it in GitHub Desktop.
Soil moisture measurement
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import spidev | |
import time | |
import os | |
from time import sleep | |
import MySQLdb | |
from time import strftime | |
# Variables for MySQL | |
db = MySQLdb.connect(host="localhost", user="root",passwd="raspberry", db="420DB") | |
cur = db.cursor() | |
# Open SPI bus | |
spi = spidev.SpiDev() | |
spi.open(0,0) | |
# Function to read SPI data from MCP3008 chip | |
# Channel must be an integer 0-7 | |
def ReadChannel(channel): | |
adc = spi.xfer2([1,(8+channel)<<4,0]) | |
data = ((adc[1]&3) << 8) + adc[2] | |
return data | |
# Define sensor channels | |
top = 0 | |
bottom = 1 | |
while True: | |
# Read the light sensor data | |
n = 0 | |
L0list = []; | |
L1list = []; | |
while (n<50): | |
L0 = ReadChannel(top) | |
L0list.append(L0) | |
L1 = ReadChannel(bottom) | |
L1list.append(L1) | |
n = n + 1 | |
else: | |
L0avg = sum(L0list) / float(len(L0list)) | |
L1avg = sum(L1list) / float(len(L1list)) | |
print L0list | |
print L1list | |
L0pc = L0*100 / 1024 | |
#light_volts = ConvertVolts(light_level,2) | |
# Read the temperature sensor data | |
L1 = ReadChannel(bottom) | |
L1pc = L1*100 / 1024 | |
datetime = (time.strftime("%Y-%m-%d ") + time.strftime("%H:%M:%S")) | |
sql = ("""INSERT INTO soil (time,leveL0,leveL1) VALUES (%s,%s,%s)""",(datetime,L0,L1)) | |
try: | |
cur.execute(*sql) | |
db.commit() | |
except: | |
db.rollback() | |
print "Failed writing to database" | |
#sql = ("""INSERT INTO soil (time,leveL0,leveL1) VALUES (%d,%d,%d)""",(datetime,L0,L1)) | |
#try: | |
#print "Writing to database..." | |
# Execute the SQL command | |
#cur.execute(*sql) | |
# Commit your changes in the database | |
#db.commit() | |
#print "Write Complete" | |
#except: | |
# Rollback in case there is any error | |
#db.rollback() | |
#print "Failed writing to database" | |
#temp_volts = ConvertVolts(temp_level,2) | |
#temp = ConvertTemp(temp_level,2) | |
print("ChanneL0 {0:4d} Percentage: {1:3}%".format (L0,L0pc)) | |
print("ChanneL1 {0:4d} Percentage: {1:3}%".format (L1,L1pc)) | |
sleep(3600) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment