def change_valve_auto(): global crop while (1): m1 = int(mcp3008.readadc(5)) m2 = int(mcp3008.readadc(6)) m3 = int(mcp3008.readadc(7)) print "Moisture level1: {:>5} ".format(m1) print "Moisture level2 : {:>5} ".format(m2) print "Moisture level3 : {:>5} ".format(m3) time.sleep(2) print crop print required_moisture_per_crop[crop] if ((m1 + m2 + m3)) > 3 * required_moisture_per_crop[crop][1]: GPIO.output(21, 1) else: GPIO.output(21, 0) req = urllib2.Request( 'http://mahikanthnag.net23.net/crop_name_retrieve.php') command_url = urllib2.urlopen(req) print "in try" command = command_url.read() print "after response" command = command.split('\n')[0] if command == 'manual': return 1
def read_accelerometer(self): '''Read the 3 axis accelerometer using the MCP3008. Each axis is tuned to show +1g when oriented towards the ground, this will be different for everyone and dependent on physical factors - mostly how flat it's mounted. The result is rounded to 2 decimal places as there is too much noise to be more accurate than this. Returns a tuple (X,Y,Z).''' x = mcp3008.readadc(0) y = mcp3008.readadc(1) z = mcp3008.readadc(2) return ( round((x-504)/102.0,2) , round((y-507)/105.0,2) , round((z-515)/102.0,2) )
def read_accelerometer(self): '''Read the 3 axis accelerometer using the MCP3008. Each axis is tuned to show +1g when oriented towards the ground, this will be different for everyone and dependent on physical factors - mostly how flat it's mounted. The result is rounded to 2 decimal places as there is too much noise to be more accurate than this. Returns a tuple (X,Y,Z).''' x = mcp3008.readadc(0) y = mcp3008.readadc(1) z = mcp3008.readadc(2) return (round((x - 504) / 102.0, 2), round( (y - 507) / 105.0, 2), round((z - 515) / 102.0, 2))
def main(): osrs_t = 1 # Temperature oversampling x 1 osrs_p = 1 # Pressure oversampling x 1 osrs_h = 1 # Humidity oversampling x 1 mode = 3 # Normal mode t_sb = 5 # Tstandby 1000ms filter = 0 # Filter off spi3w_en = 0 # 3-wire SPI Disable ctrl_meas_reg = (osrs_t << 5) | (osrs_p << 2) | mode config_reg = (t_sb << 5) | (filter << 2) | spi3w_en ctrl_hum_reg = osrs_h bus.write_byte_data(Address, 0xF2, ctrl_hum_reg) bus.write_byte_data(Address, 0xF4, ctrl_meas_reg) bus.write_byte_data(Address, 0xF5, config_reg) populate_calibration_data() while True: data_all = read_all() moist = mcp3008.readadc(5) moist = (moist*100/600) T_cloud.save_value({'value': data_all.temperature}) RH_cloud.save_value({'value': data_all.humidity}) hPA_cloud.save_value({'value': data_all.pressure}) Moist_cloud.save_value({'value': moist}) print("%7.2f hPa" % data_all.pressure) print("%7.2f RH" % data_all.humidity) print("%7.2f Degrees" % data_all.temperature) time.sleep(300)
def change_valve_auto(): global crop while (1): m1 = int(mcp3008.readadc(5)) m2 = int(mcp3008.readadc(6)) m3 = int(mcp3008.readadc(7)) print "Moisture level1: {:>5} ".format(m1) print "Moisture level2 : {:>5} ".format(m2) print "Moisture level3 : {:>5} ".format(m3) time.sleep(2) print crop print required_moisture_per_crop[crop] if ((m1 + m2 + m3)) > 3 * required_moisture_per_crop[crop][1]: GPIO.output(21, 1) else: GPIO.output(21, 0)
def thermometer(): while True: m = sensor_data = mcp3008.readadc(5) status = GPIO.input(21) # params = urllib.urlencode({'field1': sensor_data, 'key':key }) # headers = {"Content-typZZe": "application/x-www-form-urlencoded","Accept": "text/plain"} # conn = httplib.HTTPConnection("api.thingspeak.com:80") # try: # print "in try" # conn.request("POST", "/update", params, headers) # response = conn.getresponse() # print response.status, response.reason # data = response.read() # print data # print "is the data" # conn.close() # except: # print "connection failed" # break if m > 500: GPIO.output(21, 1) else: GPIO.output(21, 0) print "Moisture level: {:>5} ".format(sensor_data)
def WaterOn(): value = mcp3008.readadc(moistureCh) if value > 500: GPIO.output(12, False) else: GPIO.output(12, True)
def thermometer(): while True: m=sensor_data=mcp3008.readadc(5) status=GPIO.input(21) # params = urllib.urlencode({'field1': sensor_data, 'key':key }) # headers = {"Content-typZZe": "application/x-www-form-urlencoded","Accept": "text/plain"} # conn = httplib.HTTPConnection("api.thingspeak.com:80") # try: # print "in try" # conn.request("POST", "/update", params, headers) # response = conn.getresponse() # print response.status, response.reason # data = response.read() # print data # print "is the data" # conn.close() # except: # print "connection failed" # break if m>500: GPIO.output(21,1) else: GPIO.output(21,0) print "Moisture level: {:>5} ".format(sensor_data)
def read_distance(self): r = [] for i in range (0,10): r.append(mcp3008.readadc(self.sensor_id)) a = sum(r)/10.0 v = (a/1023.0)*3.3 d = 16.2537 * v**4 - 129.893 * v**3 + 382.268 * v**2 - 512.611 * v + 306.439 cm = int(round(d)) return cm
def read_distance(self): r = [] for i in range(0, 10): r.append(mcp3008.readadc(self.sensor_id)) a = sum(r) / 10.0 v = (a / 1023.0) * 3.3 d = 16.2537 * v**4 - 129.893 * v**3 + 382.268 * v**2 - 512.611 * v + 306.439 cm = int(round(d)) return cm
def get_distance(port=1): num_samples = 20 r = [] for i in range (0,num_samples): r.append(mcp3008.readadc(1)) a = sum(r)/float(num_samples) v = (a/1023.0)*3.3 d = 16.2537 * v**4 - 129.893 * v**3 + 382.268 * v**2 - 512.611 * v + 306.439 return int(round(d))
def get_distance(mcp3008_ch): num_samples = 10 r = [] for i in range (0,num_samples): r.append(mcp3008.readadc(mcp3008_ch, SPICLK, SPIMOSI, SPIMISO, SPICS)) a = sum(r)/float(num_samples) v = (a/1023.0)*3.3 d = 16.2537 * v**4 - 129.893 * v**3 + 382.268 * v**2 - 512.611 * v + 306.439 return int(round(d))
def get_distance(port=1): num_samples = 20 r = [] for i in range(0, num_samples): r.append(mcp3008.readadc(1)) a = sum(r) / float(num_samples) v = (a / 1023.0) * 3.3 d = 16.2537 * v**4 - 129.893 * v**3 + 382.268 * v**2 - 512.611 * v + 306.439 return int(round(d))
def get_reading(): GPIO.output(16, GPIO.HIGH) time.sleep(0.1) while True: for i in range(0, config.numchip): for j in range(0, config.numinputs): config.reading_arr[i * config.numinputs + j] = mcp3008.readadc( j, i) config.status["sensorval"] = config.reading_arr # Sleeping to let the thread finnish getting reading.(?) time.sleep(0.5) GPIO.output(16, GPIO.LOW)
def write_distance(): display.position_cursor(1, 1) r = [] for i in range(0, 10): r.append(mcp3008.readadc(1)) a = sum(r) / 10.0 v = (a / 1023.0) * 3.3 d = 16.2537 * v ** 4 - 129.893 * v ** 3 + 382.268 * v ** 2 - 512.611 * v + 306.439 cm = int(round(d)) val = "%d cm" % cm percent = int(cm / 1.5) display.ser.write(str(val).ljust(16)) display.capped_bar(16, percent)
def get_avg(sensor): # Saves 10 readings from the moisture sensor, then takes # the average and saves it as variable 'm' readings = [] num_readings = 10 while num_readings > 0: # Get current moisture readings m = mcp3008.readadc(sensor) # Save readings.append(m) num_readings = num_readings - 1 m = sum(readings) / len(readings) return m
def write_distance(): display.position_cursor(1, 1) r = [] for i in range(0, 10): r.append(mcp3008.readadc(1)) a = sum(r) / 10.0 v = (a / 1023.0) * 3.3 d = 16.2537 * v**4 - 129.893 * v**3 + 382.268 * v**2 - 512.611 * v + 306.439 cm = int(round(d)) val = '%d cm' % cm percent = int(cm / 1.5) display.ser.write(str(val).ljust(16)) display.capped_bar(16, percent)
def get_distance2(mcp3008_ch): num_samples = 10 r = [] for i in range (0,num_samples): r.append(mcp3008.readadc(mcp3008_ch, SPICLK, SPIMOSI, SPIMISO, SPICS)) a = sum(r)/float(num_samples) sensorRet = mcp3008.readadc(mcp3008_ch, SPICLK, SPIMOSI, SPIMISO, SPICS) sensorRet = sensorRet * 500 / 1023 if(sensorRet == 0): sensorRet = 1 sensorRet = 3200 / sensorRet-3 return int(sensorRet) #This method involves using mcp3008 with the SPI drivers. #No GPIO are used, and all sensors are connected to #mcp3008 channels 0-7 #
def change_valve_auto(): global crop while(1): m1 = int(mcp3008.readadc(5)) m2 = int(mcp3008.readadc(6)) m3 = int(mcp3008.readadc(7)) print "Moisture level1: {:>5} ".format(m1) print "Moisture level2 : {:>5} ".format(m2) print "Moisture level3 : {:>5} ".format(m3) time.sleep(2); print crop print required_moisture_per_crop[crop] if ((m1+m2+m3))>3*required_moisture_per_crop[crop][1]: GPIO.output(21,1) else: GPIO.output(21,0) req=urllib2.Request('http://mahikanthnag.net23.net/crop_name_retrieve.php') command_url = urllib2.urlopen(req) print "in try" command =command_url.read() print "after response" command= command.split('\n')[0] if command=='manual' : return 1
SPIMISO = 9 SPIMOSI = 10 SPICS = 22 # 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) # ph probe connected to adc #0 ph_adc = 0 while True: # read the analog pin ph_val = mcp3008.readadc(ph_adc, SPICLK, SPIMOSI, SPIMISO, SPICS) ph_ListCounts.append(ph_val) print(len(ph_ListCounts), ":", ph_val) # once we hit our desired sample size ph_ListLength (ie: 120) # then calculate the average value if len(ph_ListCounts) >= ph_ListLength: ph_FilteredCounts = numpy.array(ph_ListCounts) ph_FilteredMean = numpy.mean(ph_FilteredCounts, axis=0) ph_FlteredSD = numpy.std(ph_FilteredCounts, axis=0) ph_FilteredCountList = [ x for x in ph_FilteredCounts if (x >= ph_FilteredMean - ph_Sigma * ph_FlteredSD) ] ph_FilteredCountList = [ x for x in ph_FilteredCountList
def readThermistor(thermistorPIN): thermistorValue=mcp3008.readadc(thermistorPIN, constants.SPICLK, constants.SPIMOSI, constants.SPIMISO, constants.SPICS) return thermistorValue
def getMoisture(): mcpMoisture = mcp3008.readadc(mcpPin) return mcpMoisture
def getAnalog(self): thermistorValue=mcp3008.readadc(self.thermistorPin, constants.SPICLK, constants.SPIMOSI, constants.SPIMISO, constants.SPICS) return thermistorValue
), "\r\n") #send the email server = smtplib.SMTP('smtp.mail.yahoo.co.uk:587') server.login(username,password) server.sendmail(fromaddr, toaddr, BODY) server.quit() ################################################################################################### #Program Variables start hear ################################################################################################### try: while True: # Variables battery1 = mcp3008.readadc(0) battery2 = mcp3008.readadc(2) minute = time.strftime("%M") volts1 = battery1 * ( 15 / 1024.0) voltstring1 = str(volts1)[0:5] volts2 = battery2 * ( 15 / 1024.0) voltstring2 = str(volts2)[0:5] # Check Battery 2 avalibilty if volts2 > batterycutoff2: battery2avaliable = "Yes" else: battery2avaliable = "No" #1. Battery 1 Low voltage and Battery 2 Not avaliable
from __future__ import division import mcp3008 import sys def ConvertTemp(data,places): temp = ((data * 330)/float(1023))-50 temp = round(temp,places) return temp def ConvertTempCtoF(data): temp = (((data * 9) / 5) + 32) return temp def ConvertMoistureToPercent(data): percent = ((data / 1024) * 100) return percent temp_channel=0 moisture_channel=1 light_channel=2 sensorVal = mcp3008.readadc(1) sensorPrcnt = ConvertMoistureToPercent(sensorVal) print "Sensor Value: ", sensorVal print "Sensor Percent: ", sensorPrcnt
def getMoisture(self): return mcp3008.readadc(self.pin)
def calculatemoisture(self): soil_moisture = mcp3008.readadc( moisturepin) #taking soilmoisture value from adc pin 5 soil_moisture = (soil_moisture * 100) / 1024 soil_moisture = 100 - soil_moisture return soil_moisture
plant2.stopmotor() else: plant1.stopmotor() plant2.stopmotor() print Raspmessage plant1.stopmotor() #off the motors initially plant2.stopmotor() soil_moisture1 = plant1.calculatemoisture() #print "soil moisture1:",soil_moisture1 soil_moisture2 = plant2.calculatemoisture( ) #taking soilmoisture value from adc pin 6 #print "soil moisture2:",soil_moisture2 humidity, temperature = Adafruit_DHT.read_retry(11, 4) #print "humidity:",humidity #print "temperature:",temperature watersensor_reading = mcp3008.readadc( 0) #taking water sensor reading value from adc pin 0 #print watersensor_reading if (watersensor_reading >= 15): print("Raining") k = 0 else: print("not Raining") k = 1 distance = calculate_tankheight() print "------------------------------------------------" print "humidity: ", humidity, "temperature: ", temperature print "soil moisture of plant 0:", soil_moisture1 print "soil moisture of plant 1:", soil_moisture2 print "distance:", distance print "water sensor:", watersensor_reading print "------------------------------------------------"
import requests, json import Adafruit_DHT import sys, mcp3008 import motor import sys import time from ultra_sonic_sensor import get_distance from motor import run_motor bucket = 70 while True: humidity, temperature = Adafruit_DHT.read_retry(11, 4) moisture = mcp3008.readadc(5) distance = get_distance() distance = (1 - distance / bucket) * 100 print(humidity, temperature, moisture, distance) #run_motor(moisture) '''url = 'http://127.0.0.1:8100/weather/json/' payload = {'data':str(temperature) + ', ' + str(humidity) + ', ' + str(moisture) + ", " + str(distance)} r = requests.post(url,data = payload)''' time.sleep(2)
def apploop(self): while True: #defs_common.logtoconsole("app loop") ########################################################################################## # read ds18b20 temperature sensor # # we support multiple probes, so work from the probe dictionary and get data # for each ########################################################################################## # read data from the temperature probes if (int(round(time.time() * 1000)) - self.AppPrefs.ds18b20_SamplingTimeSeed ) > self.AppPrefs.ds18b20_SamplingInterval: for p in self.AppPrefs.tempProbeDict: try: timestamp = datetime.now() dstempC = float( ds18b20.read_temp( self.AppPrefs.tempProbeDict[p].probeid, "C")) dstempF = defs_common.convertCtoF(float(dstempC)) dstempF = float(dstempF) tempData = str(dstempC) + "," + str(dstempF) if str(self.AppPrefs.temperaturescale) == str( defs_common.SCALE_F): broadcasttemp = str("%.1f" % dstempF) else: broadcasttemp = str("%.1f" % dstempC) #self.tempProbeDict[p].lastLogTime = self.ds18b20_LastLogTimeDict # json_body = [ # { # "measurement": "probevalues", # "tags": { # "appuid": self.AppPrefs.appuid, # "probeid": "ds18b20_" + self.AppPrefs.tempProbeDict[p].probeid # }, # "time": datetime.utcnow(), # "fields": { # "value": float(dstempC), # } # } # ] if (int(round(time.time() * 1000)) - int(self.AppPrefs.tempProbeDict[p].lastLogTime) ) > self.AppPrefs.ds18b20_LogInterval: # log and broadcast temperature value defs_common.logprobedata( "ds18b20_" + self.AppPrefs.tempProbeDict[p].probeid + "_", tempData) defs_common.logtoconsole( "***Logged*** [ds18b20_" + self.AppPrefs.tempProbeDict[p].probeid + "] " + self.AppPrefs.tempProbeDict[p].name + str(" = {:.1f}".format(dstempC)) + " C | " + str("{:.1f}".format(dstempF)) + " F", fg="CYAN", style="BRIGHT") self.logger.info( str("***Logged*** [ds18b20_" + self.AppPrefs.tempProbeDict[p].probeid + "] " + self.AppPrefs.tempProbeDict[p].name + str(" = {:.1f}".format(dstempC)) + " C | " + str("{:.1f}".format(dstempF))) + " F") # log to InfluxDB # self.WriteDataInfluxDB(json_body) self.WriteProbeDataInfluxDB( "ds18b20_" + self.AppPrefs.tempProbeDict[p].probeid, dstempC) #self.broadcastProbeStatus("ds18b20", "ds18b20_" + self.AppPrefs.tempProbeDict[p].probeid, str(broadcasttemp), self.AppPrefs.tempProbeDict[p].name) #self.ds18b20_LastLogTimeDict = int(round(time.time()*1000)) self.AppPrefs.tempProbeDict[p].lastLogTime = int( round(time.time() * 1000)) #self.AppPrefs.tempProbeDict[p].lastTemperature = dstempC self.AppPrefs.tempProbeDict[ p].lastTemperature = broadcasttemp else: self.logger.info( str("[ds18b20_" + self.AppPrefs.tempProbeDict[p].probeid + "] " + self.AppPrefs.tempProbeDict[p].name + str(" = {:.1f}".format(dstempC)) + " C | " + str("{:.1f}".format(dstempF))) + " F") # broadcast temperature value # self.MQTTclient.publish("reefberrypi/demo",str(dstempC)) self.broadcastProbeStatus( "ds18b20", "ds18b20_" + str(self.AppPrefs.tempProbeDict[p].probeid), str(broadcasttemp), self.AppPrefs.tempProbeDict[p].name) self.AppPrefs.tempProbeDict[ p].lastTemperature = broadcasttemp except Exception as e: defs_common.logtoconsole( str("<<<Error>>> Can not read ds18b20_" + self.AppPrefs.tempProbeDict[p].probeid + " temperature data!"), fg="WHITE", bg="RED", style="BRIGHT") self.logger.error( "<<<Error>>> Can not read ds18b20_" + self.AppPrefs.tempProbeDict[p].probeid + " temperature data!") self.logger.error(e) # record the new sampling time self.AppPrefs.ds18b20_SamplingTimeSeed = int( round(time.time() * 1000)) # convert time to milliseconds ################################################################################################################ # read dht11 temperature and humidity sensor # # these sensors are slow to refresh and should not be read more # than once every second or two (ie: dht_SamplingInterval = 3000ms or 5000ms for 3s or 5s) would be safe ################################################################################################################ if self.AppPrefs.DHT_Sensor.get("enabled") == "True": if (int(round(time.time() * 1000)) - self.AppPrefs.DHT_Sensor.get("dht11_samplingtimeseed") ) > int( self.AppPrefs.DHT_Sensor.get( "dht11_samplinginterval")): # let's read the dht11 temp and humidity data result = self.dht_sensor.read() if result.is_valid(): temp_c = result.temperature temp_f = defs_common.convertCtoF(float(temp_c)) temp_f = float(temp_f) hum = result.humidity timestamp = datetime.now() if str(self.AppPrefs.temperaturescale) == str( defs_common.SCALE_F): broadcasttemp = str("%.1f" % temp_f) else: broadcasttemp = str("%.1f" % temp_c) if (int(round(time.time() * 1000)) - self.AppPrefs. DHT_Sensor.get("dht11_lastlogtime")) > int( self.AppPrefs.DHT_Sensor.get( "dht11_loginterval")): tempData = str( "{:.1f}".format(temp_c)) + "," + str(temp_f) # log and broadcast temperature value defs_common.logprobedata("dht_t_", tempData) defs_common.logtoconsole( "***Logged*** [dht_t] " + self.AppPrefs.DHT_Sensor.get( "temperature_name") + " = %.1f C" % temp_c + " | %.1f F" % temp_f, fg="CYAN", style="BRIGHT") self.logger.info( str("***Logged*** [dht_t] " + self.AppPrefs.DHT_Sensor.get( "temperature_name") + " = %.1f C" % temp_c + " | %.1f F" % temp_f)) self.broadcastProbeStatus( "dht", "dht_t", str(broadcasttemp), self.AppPrefs.DHT_Sensor.get( "temperature_name")) # json_body = [ # { # "measurement": "probevalues", # "tags": { # "appuid": self.AppPrefs.appuid, # "probeid": "dht_t" # }, # "time": datetime.utcnow(), # "fields": { # "value": float(temp_c), # } # } # ] # log to InfluxDB # self.WriteDataInfluxDB(json_body) self.WriteProbeDataInfluxDB("dht_t", temp_c) # log and broadcast humidity value defs_common.logprobedata("dht_h_", "{:.0f}".format(hum)) defs_common.logtoconsole( "***Logged*** [dht_h] " + self.AppPrefs.DHT_Sensor.get("humidity_name") + " = %d %%" % hum, fg="CYAN", style="BRIGHT") self.logger.info( str("***Logged*** [dht_h] " + self.AppPrefs.DHT_Sensor.get( "humidity_name") + " = %d %%" % hum)) self.broadcastProbeStatus( "dht", "dht_h", str(hum), self.AppPrefs.DHT_Sensor.get("humidity_name")) # json_body = [ # { # "measurement": "probevalues", # "tags": { # "appuid": self.AppPrefs.appuid, # "probeid": "dht_h" # }, # "time": datetime.utcnow(), # "fields": { # "value": float(hum), # } # } # ] # log to InfluxDB # self.WriteDataInfluxDB(json_body) self.WriteProbeDataInfluxDB("dht_h", hum) self.AppPrefs.DHT_Sensor[ "dht11_lastlogtime"] = int( round(time.time() * 1000)) else: self.logger.info( str("[dht_t] " + self.AppPrefs.DHT_Sensor.get( "temperature_name") + " = %.1f C" % temp_c + " | %.1f F" % temp_f)) self.logger.info( str("[dht_h] " + self.AppPrefs.DHT_Sensor.get( "humidity_name") + " = %d %%" % hum)) # broadcast humidity value self.broadcastProbeStatus( "dht", "dht_h", str(hum), self.AppPrefs.DHT_Sensor.get("humidity_name")) # broadcast temperature value self.broadcastProbeStatus( "dht", "dht_t", str(broadcasttemp), self.AppPrefs.DHT_Sensor.get( "temperature_name")) # record the new sampling time self.AppPrefs.DHT_Sensor[ "dht11_samplingtimeseed"] = int( round(time.time() * 1000)) # convert time to milliseconds ########################################################################################## # read each of the 8 channels on the mcp3008 # channels (0-7) ########################################################################################## # only read the data at every ph_SamplingInterval (ie: 500ms or 1000ms) if (int(round(time.time() * 1000)) - self.AppPrefs.dv_SamplingTimeSeed ) > self.AppPrefs.dv_SamplingInterval: # for x in range (0,8): for ch in self.AppPrefs.mcp3008Dict: if self.AppPrefs.mcp3008Dict[ch].ch_enabled == "True": #defs_common.logtoconsole(str(self.mcp3008Dict[ch].ch_num) + " " + str(self.mcp3008Dict[ch].ch_name) + " " + str(self.mcp3008Dict[ch].ch_enabled) + " " + str(len(self.mcp3008Dict[ch].ch_dvlist))) dv = mcp3008.readadc( int(self.AppPrefs.mcp3008Dict[ch].ch_num), GPIO_config.SPICLK, GPIO_config.SPIMOSI, GPIO_config.SPIMISO, GPIO_config.SPICS) self.AppPrefs.mcp3008Dict[ch].ch_dvlist.append(dv) #self.logger.info(str(self.mcp3008Dict[ch].ch_num) + " " + str(self.mcp3008Dict[ch].ch_name) + " " + str(self.mcp3008Dict[ch].ch_dvlist)) # once we hit our desired sample size of ph_numsamples (ie: 120) # then calculate the average value if len(self.AppPrefs.mcp3008Dict[ch].ch_dvlist) >= int( self.AppPrefs.mcp3008Dict[ch].ch_numsamples): # The probes may pick up noise and read very high or # very low values that we know are not good values. We are going to use numpy # to calculate the standard deviation and remove the outlying data that is # Sigma standard deviations away from the mean. This way these outliers # do not affect our results self.logger.info( "mcp3008 ch" + str(self.AppPrefs.mcp3008Dict[ch].ch_num) + " raw data " + str(self.AppPrefs.mcp3008Dict[ch].ch_name) + " " + str(self.AppPrefs.mcp3008Dict[ch].ch_dvlist)) dv_FilteredCounts = numpy.array( self.AppPrefs.mcp3008Dict[ch].ch_dvlist) dv_FilteredMean = numpy.mean(dv_FilteredCounts, axis=0) dv_FlteredSD = numpy.std(dv_FilteredCounts, axis=0) dv_dvlistfiltered = [ x for x in dv_FilteredCounts if (x > dv_FilteredMean - float(self.AppPrefs.mcp3008Dict[ch].ch_sigma) * dv_FlteredSD) ] dv_dvlistfiltered = [ x for x in dv_dvlistfiltered if (x < dv_FilteredMean + float(self.AppPrefs.mcp3008Dict[ch].ch_sigma) * dv_FlteredSD) ] self.logger.info( "mcp3008 ch" + str(self.AppPrefs.mcp3008Dict[ch].ch_num) + " filtered " + str(self.AppPrefs.mcp3008Dict[ch].ch_name) + " " + str(dv_dvlistfiltered)) # calculate the average of our filtered list try: dv_AvgCountsFiltered = int( sum(dv_dvlistfiltered) / len(dv_dvlistfiltered)) # delete this line print("{:.2f}".format(dv_AvgCountsFiltered)) except: # need to revisit this error handling. Exception thrown when all dv_AvgCountsFiltered = 1 # values were 1023 print("Error collecting data") # self.mcp3008Dict[ch].ch_dvlist.clear() ## delete this line if self.AppPrefs.mcp3008Dict[ch].ch_type == "pH": # bug, somtimes value is coming back high, like really high, like 22.0. this is an impossible # value since max ph is 14. need to figure this out later, but for now, lets log this val to aid in # debugging orgval = dv_AvgCountsFiltered # convert digital value to ph lowCal = self.AppPrefs.mcp3008Dict[ch].ch_ph_low medCal = self.AppPrefs.mcp3008Dict[ch].ch_ph_med highCal = self.AppPrefs.mcp3008Dict[ch].ch_ph_high dv_AvgCountsFiltered = ph_sensor.dv2ph( dv_AvgCountsFiltered, ch, lowCal, medCal, highCal) dv_AvgCountsFiltered = float( "{:.2f}".format(dv_AvgCountsFiltered)) if dv_AvgCountsFiltered > 14: self.logger.error("Invalid PH value: " + str(dv_AvgCountsFiltered) + " " + str(orgval) + " " + str(dv_dvlistfiltered)) defs_common.logtoconsole( "Invalid PH value: " + str(dv_AvgCountsFiltered) + " " + str(orgval) + " " + str(dv_dvlistfiltered), fg="RED", style="BRIGHT") # if enough time has passed (ph_LogInterval) then log the data to file # otherwise just print it to console timestamp = datetime.now() if (int(round(time.time() * 1000)) - self.AppPrefs.mcp3008Dict[ch].LastLogTime ) > self.AppPrefs.dv_LogInterval: # sometimes a high value, like 22.4 gets recorded, i need to fix this, but for now don't log that # if ph_AvgFiltered < 14.0: #RBP_commons.logprobedata(config['logs']['ph_log_prefix'], "{:.2f}".format(ph_AvgFiltered)) # log data to InfluxDB self.WriteProbeDataInfluxDB( "mcp3008_ch" + str(self.AppPrefs.mcp3008Dict[ch].ch_num), "{:.2f}".format(dv_AvgCountsFiltered)) defs_common.logprobedata( "mcp3008_ch" + str(self.AppPrefs.mcp3008Dict[ch].ch_num) + "_", "{:.2f}".format(dv_AvgCountsFiltered)) print( timestamp.strftime(Fore.CYAN + Style.BRIGHT + "%Y-%m-%d %H:%M:%S") + " ***Logged*** dv = " + "{:.2f}".format(dv_AvgCountsFiltered) + Style.RESET_ALL) self.AppPrefs.mcp3008Dict[ch].LastLogTime = int( round(time.time() * 1000)) else: print( timestamp.strftime("%Y-%m-%d %H:%M:%S") + " dv = " + "{:.2f}".format(dv_AvgCountsFiltered)) self.broadcastProbeStatus( "mcp3008", "mcp3008_ch" + str(self.AppPrefs.mcp3008Dict[ch].ch_num), str(dv_AvgCountsFiltered), str(self.AppPrefs.mcp3008Dict[ch].ch_name)) self.AppPrefs.mcp3008Dict[ch].lastValue = str( dv_AvgCountsFiltered) # clear the list so we can populate it with new data for the next data set self.AppPrefs.mcp3008Dict[ch].ch_dvlist.clear() # record the new sampling time self.AppPrefs.dv_SamplingTimeSeed = int( round(time.time() * 1000)) # convert time to milliseconds ########################################################################################## # pause to slow down the loop, otherwise CPU usage spikes as program is busy waiting ########################################################################################## time.sleep(.5)
#### Please input saveWaterMode=1 if you want to turn on this mode. input 0 if you want to turn off this mode. s2 = 0 #### Please set (IN HOURS) how often you want your algorithm to repeat r2 = 10 #set to 10, originally should be 0.5 while True: GPIO.setmode(GPIO.BOARD) GPIO.setup(16, GPIO.OUT) GPIO.output(16, GPIO.LOW) GPIO.setwarnings(False) ## CHECKING FOR MOISTURE READING AT TIME = 0 ## m0_b = mcp3008.readadc(mcpPin) reading0 = str(m0_b) humi_b, temp_b = Adafruit_DHT.read_retry(dhtSensor, dhtPin) h0_b = str(humi_b) print("Moisture level is: " + reading0) #Take a reading at time [t] while True: if s2==1: print ("Save Water Mode is: ON") print ("Humidity is: " + h0_b) else: print ("Save Water Mode is OFF") break if m0_b > critMoist2:
import sys sys.path.append('/home/pi/py/Adafruit-Raspberry-Pi-Python-Code/Adafruit_CharLCDPlate') from time import sleep from Adafruit_CharLCDPlate import Adafruit_CharLCDPlate import mcp3008 lcd = Adafruit_CharLCDPlate() while True: m = mcp3008.readadc(5) try: lcd.home() lcd.message("Moisture level:\n%d " % m) if m < 150: lcd.backlight(lcd.RED) elif m < 500: lcd.backlight(lcd.YELLOW) else: lcd.backlight(lcd.GREEN) except IOError as e: print e sleep(.5)
def write_pots(): display.position_cursor(1, 1) val = mcp3008.readadc(0) percent = int(val / 10.23) display.ser.write(str(val).ljust(16)) display.capped_bar(16, percent)
# Xively variables to publish data on web # specifc to amanazad account @ http://www.xivley.com API_KEY = "DhYvcI3WAbO1o5sKk9p7e47Q9bcptc5r81c2NX87RA72ZR" FEEDID = 1141885015 # pins on MCP3008 to sensors phototransPIN = 0 thermistorPIN = 2 # main # run with 1min load average from Xively try: while True: # read raw analog values (0-1023, 2^10) read_Phototrans = mcp3008.readadc(phototransPIN, SPICLK, SPIMOSI, SPIMISO, SPICS) # convert analog to lumens lumens = (read_Phototrans - 180) * 1.99 read_Thermistor = mcp3008.readadc(thermistorPIN, SPICLK, SPIMOSI, SPIMISO, SPICS) # convert analog to C temp_C = 25 + ((read_Thermistor - 520) / 4) # convert C to F temp_F = ((temp_C * 9) / 5) + 32 # print out values to terminal if DEBUG: print "Phototransistor Analog Value = ", read_Phototrans print "Lumens: ", lumens print "" print "Thermistor Analog Value = ", read_Thermistor
light_channel=2 sleepVal=60 mysql_host='gardenpi1.lgmt.teknofile.net' mysql_port=3306 mysql_user='******' mysql_pass='******' mysql_db='garden' # Clear the screen and put the cursor at the top #print '\x1b[2J\x1b[H' #print 'Moisture sensor' #print '===============\n' while True: tempVal = mcp3008.readadc(temp_channel) moistureVal = mcp3008.readadc(moisture_channel) print "Temp Value: ", tempVal print "Moisture Value: ", moistureVal db = MySQLdb.connect("elk.lgmt.teknofile.net", "gardenpi1", "temppass", "garden"); cur = db.cursor() insert_query = ( "INSERT INTO sensor_data (sensor_name, sensor_type, sensor_val) " "VALUES('gardenpitemp', 'temp', " + str(tempVal) + ")") cur.execute(insert_query) insert_query = ( "INSERT INTO sensor_data (sensor_name, sensor_type, sensor_val) "
#### Please input saveWaterMode=1 if you want to turn on this mode. input 0 if you want to turn off this mode. s = 1 #### Please set (IN HOURS) how often you want your algorithm to repeat r = 10 #set to 10, originally should be 0.5 while True: GPIO.setmode(GPIO.BOARD) GPIO.setup(36, GPIO.OUT) GPIO.output(36, GPIO.HIGH) GPIO.setwarnings(False) ## CHECKING FOR MOISTURE READING AT TIME = 0 ## m0 = mcp3008.readadc(mcpPin) reading0 = str(m0) humi, temp = Adafruit_DHT.read_retry(dhtSensor, dhtPin) h0 = str(humi) print("Moisture level is: " + reading0) #Take a reading at time [t] while True: if s==1: print ("Save Water Mode is: ON") print ("Humidity is: " + h0) else: print ("Save Water Mode is OFF") break if m0 > critMoist1:
def getHumidity(self): humidity=mcp3008.readadc(self.tensiometerPin, constants.SPICLK, constants.SPIMOSI, constants.SPIMISO, constants.SPICS) return humidity
def getMoisture2(): mcpMoisture2 = mcp3008.readadc(mcpPin2) return mcpMoisture2
def getAnalog(self): phototransValue=mcp3008.readadc(self.phototransistorPin, constants.SPICLK, constants.SPIMOSI, constants.SPIMISO, constants.SPICS) return phototransValue
def readTensiometer(tensiometerPIN): humidity=mcp3008.readadc(tensiometerPIN, constants.SPICLK, constants.SPIMOSI, constants.SPIMISO, constants.SPICS) return humidity
"The Up time is: " + get_up_stats()[0]), "\r\n") #send the email server = smtplib.SMTP('smtp.mail.yahoo.co.uk:587') server.login(username, password) server.sendmail(fromaddr, toaddr, BODY) server.quit() ################################################################################################### #Program Variables start hear ################################################################################################### try: while True: # Variables battery1 = mcp3008.readadc(0) battery2 = mcp3008.readadc(2) minute = time.strftime("%M") volts1 = battery1 * (15 / 1024.0) voltstring1 = str(volts1)[0:5] volts2 = battery2 * (15 / 1024.0) voltstring2 = str(volts2)[0:5] # Check Battery 2 avalibilty if volts2 > batterycutoff2: battery2avaliable = "Yes" else: battery2avaliable = "No" #1. Battery 1 Low voltage and Battery 2 Not avaliable if batteryselect == 1: if volts1 <= batterycutoff1:
def readPhototransistor(phototransPIN): phototransValue=mcp3008.readadc(phototransPIN, constants.SPICLK, constants.SPIMOSI, constants.SPIMISO, constants.SPICS) return phototransValue
import sys sys.path.append( '/home/pi/py/Adafruit-Raspberry-Pi-Python-Code/Adafruit_CharLCDPlate') from time import sleep from Adafruit_CharLCDPlate import Adafruit_CharLCDPlate import mcp3008 lcd = Adafruit_CharLCDPlate() while True: m = mcp3008.readadc(5) try: lcd.home() lcd.message("Moisture level:\n%d " % m) if m < 150: lcd.backlight(lcd.RED) elif m < 500: lcd.backlight(lcd.YELLOW) else: lcd.backlight(lcd.GREEN) except IOError as e: print e sleep(.5)
output = subprocess.check_output("./loldht") print output matches = re.search("Humidity =\s+([0-9.]+)", output) if (not matches): time.sleep(3) continue humidity = float(matches.group(1)) # search for humidity printout matches = re.search("Temperature =\s+([0-9.]+)", output) if (not matches): time.sleep(3) continue temp = float(matches.group(1)) r = RCtime(25) soil = mcp3008.readadc(5) if(r > 50): light = "OFF" else: light = "ON" rtime = strftime("%Y-%m-%d %H:%M:%S", gmtime()) print "Temperature: %.1f C" % temp print "Humidity: %.1f %%" % humidity print light print r print soil print rtime
def get_reading(numchip=2): reading_arr = [0] * numchip * 8 for i in range(0, numchip): for j in range(0, 8): reading_arr[i * 8 + j] = mcp3008.readadc(j, i) return reading_arr
def getmoisture(self): #the 5 here corresponds to the port on the mcp3008 chip which converts #analog to digital. return mcp3008.readadc(5)