def main(): sensor = DS18B20() while True: time = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S') temperatures = sensor.get_temperatures( [DS18B20.DEGREES_C, DS18B20.DEGREES_F, DS18B20.KELVIN]) print time print("Degrees Celsius: %f" % temperatures[0]) print("Kelvin: %f" % temperatures[2]) print("Degrees Fahrenheit: %f" % temperatures[1]) print("Adding row please wait...") x = 0 try: for values in wks.col_values(1): ## loop count row x = x + 1 rowToAdd = [ time, temperatures[0], temperatures[2], temperatures[1] ] ## your data want to send wks.resize(x) wks.append_row(rowToAdd) print("Add row done !!!") print("==================================") sleep(5) except: print("Exit.") print("Bye...") break
def getTemperatureStats(temperaturesensors): try: for temperaturesensor in temperaturesensors: if temperaturesensor['type'] == "temperature": avg = 0 summation = 0 rowCount = 0 temperature = 0 temperaturesensor['temperature'] = float("%.2f" % ( DS18B20(str(temperaturesensor['address'])).get_temperature( DS18B20.DEGREES_F) + temperaturesensor['temperaturecorrection'])) if temperaturesensor['pin']: ps = subprocess.Popen( ('gpio', '-g', 'read', str(temperaturesensor['pin'])), stdout=subprocess.PIPE, bufsize=1, universal_newlines=True) output = str(ps.communicate()) output = output.translate(None, "\n',N('on\e) ") if output == "1": temperaturesensor['pinstatus'] = "Off" if output == "0": temperaturesensor['pinstatus'] = "On" return temperaturesensors except: print "Error getting sensor status."
def checkTemp(self): if (config.TEMP_ENABLED): sensor = DS18B20() temperatures = sensor.get_temperatures( [DS18B20.DEGREES_C, DS18B20.DEGREES_F, DS18B20.KELVIN]) if (temperatures[1] >= config.TEMP_MAX_F) or (temperatures[0] >= TEMP_MAX_C): self.n.sendAlert(3)
def sensor_setup(all_settings): ds = DS18B20() if all_settings['mpu6050_settings']['i2c_addr'] == 68: mpu_addr = 0x68 mpu = mpu6050(mpu_addr) pump = relays(all_settings['pump_settings']) heater = relays(all_settings['heater_settings']) return ds, mpu, pump, heater
def __init__(self, period, sample_q=None): self.period = period self.sample_q = sample_q or queue.Queue() self._sensor = DS18B20() self._thread = None self._stop_event = threading.Event() self._sampling_time = 0 # how long it takes to read sensor self._timeout = self.period - self._sampling_time
def before_all(): # mock sensors DS18B20.BASE_DIRECTORY = world.MOCKED_SENSORS_DIR sensors = [] sensor_ids = DS18B20.get_available_sensors() for sensor_id in sensor_ids: sensors.append(DS18B20(sensor_id, load_kernel_modules=False)) world.sensors = sensors
def main(): sensor = DS18B20() while True: temperatures = sensor.get_temperatures([DS18B20.DEGREES_C, DS18B20.DEGREES_F, DS18B20.KELVIN]) print("Kelvin: %f" % temperatures[2]) print("Degrees Celsius: %f" % temperatures[0]) print("Degrees Fahrenheit: %f" % temperatures[1]) print("=====================================") sleep(1)
def __init__(self, histories={}, minimum_period = 60, sample_q=None): self.minimum_period = minimum_period self.latest = Sample("No data") self.histories = histories self._sensor = DS18B20() self.stopping_ev = threading.Event() self._sampling_time = 0 self.sample_q = sample_q or queue.Queue()
def getTemp(temp): if (config.TEMP_ENABLED): sensor = DS18B20() temperatures = sensor.get_temperatures( [DS18B20.DEGREES_C, DS18B20.DEGREES_F, DS18B20.KELVIN]) if (temp == 0): return str(temperatures[1]) if (temp == 1): return str(temperatures[0]) return temperatures return 'No Sensor'
def main(): sensor = DS18B20() print("=====================================") temperatures = sensor.get_temperatures( [DS18B20.DEGREES_C, DS18B20.DEGREES_F, DS18B20.KELVIN]) print("Kelvin: %f" % temperatures[2]) print("Temp C : %f" % temperatures[0]) print("Degrees Fahrenheit: %f" % temperatures[1]) print("=====================================")
def __init__(self, scheduler, model, temp_period, pic_period, readings): self.task = scheduler self.spabModel = model self.temp_p = temp_period self.pic_p = pic_period self.readings = readings self.temp_sensor = DS18B20() #self.camera = PiCamera() #self.camera.resolution = (320, 240) #self.camera.start_preview() i2c = busio.I2C(board.SCL, board.SDA) self.ads = ADS.ADS1115(i2c) self.chan = AnalogIn(self.ads, ADS.P0)
def __init__(self,type=sensorType.FAKE,pin=None): # types are self.temp = 80 self.reads = 0 self.change = .1 self.pin = pin # need to add some error/bound checking here!!! if type == sensorType.DS18B20: self.sensor = DS18B20() elif type == sensorType.DHT11: self.sensor = DHTXX(type=sensorType.DHT11,pin=self.pin) elif type == sensorType.DHT22: self.sensor = DHTXX(type=sensorType.DHT22,pin=self.pin) else: self.sensor = None
def main(tank_id): logging.basicConfig(filename='main.log', format="%(asctime)s %(levelname)s: %(message)s",level=logging.DEBUG) ds_object = DS18B20() while True: #Read sensors sensor1 = read_sensor1(ds_object) sensor2 = read_sensor2(ds_object) #Transmit to google app engine try: transmit(tank_id, sensor1, sensor2) except: logging.debug('Could not transmit!') #Sleepy weepy! time.sleep(60)
def main(): esp.osdebug(None) config = load_config() broadcaster = Broadcaster(100) one_wire = onewire.OneWire(machine.Pin(22, machine.Pin.PULL_UP)) temp_sensor = DS18B20(one_wire) sensor_ids = temp_sensor.scan() if not sensor_ids: machine.reset() return sensor_id = sensor_ids[0] try: temperature = temp_sensor.convert_read_temp(sensor_id) broadcaster.broadcast(temperature) except Exception: broadcaster.broadcast(Broadcaster.ERROR_TEMPERATURE) measure("end") machine.reset()
def getTemperatureStats(temperaturesensors, tempCSVpath, tempCSV): try: for temperaturesensor in temperaturesensors: if temperaturesensor['type'] == "temperature": avg = 0 summation = 0 rowCount = 0 temperature = 0 temperaturesensor['temperature'] = float("%.2f" % ( DS18B20(str(temperaturesensor['address'])).get_temperature( DS18B20.DEGREES_F) + temperaturesensor['temperaturecorrection'])) with open(tempCSVpath + tempCSV, 'r') as csvfile: csvreader = csv.reader(csvfile) next(csvreader) for row in csvreader: summation = float(row[int( temperaturesensor['csvid'])]) + summation rowCount += 1 csvfile.close() avg = summation / rowCount temperaturesensor['temperatureaverage'] = str("%.2f" % avg) if temperaturesensor['pin']: ps = subprocess.Popen( ('gpio', '-g', 'read', str( temperaturesensor['pin'])), stdout=subprocess.PIPE, bufsize=1, universal_newlines=True) output = str(ps.communicate()) output = output.translate(None, "\n',N('on\e) ") if output == "1": temperaturesensor['pinstatus'] = "Off" if output == "0": temperaturesensor['pinstatus'] = "On" return temperaturesensors except: print "Error getting sensor status."
redisPrefix = "flaskheat" #get Generlasettings generalSettings = redis_connector.redisCmdHgetAll(redisPrefix + ':general') #Set Relay pin relayPin = int(generalSettings['relayGpio']) GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(relayPin, GPIO.OUT) days = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] relay = int(generalSettings['relay']) sensor = DS18B20() temperature = round(sensor.get_temperature(), 3) print("The temperature is %s celsius" % temperature) #Save temp on redis redis_connector.redisCmdHset(redisPrefix + ':general', 'lastTemp', temperature) delta = float(generalSettings['delta']) #set historical temp if enabled if generalSettings['enableHistoricalData'] == 'true': timestamp = int(time.time()) print( timestamp, datetime.datetime.fromtimestamp(timestamp).strftime(
in_btn_left = 13 in_btn_right = 20 in_btn_up = 26 in_btn_down = 16 GPIO.setup(in_btn_red, GPIO.IN, GPIO.PUD_DOWN) GPIO.setup(in_btn_green, GPIO.IN, GPIO.PUD_DOWN) GPIO.setup(in_btn_blue, GPIO.IN, GPIO.PUD_DOWN) GPIO.setup(in_btn_left, GPIO.IN, GPIO.PUD_DOWN) GPIO.setup(in_btn_right, GPIO.IN, GPIO.PUD_DOWN) GPIO.setup(in_btn_up, GPIO.IN, GPIO.PUD_DOWN) GPIO.setup(in_btn_down, GPIO.IN, GPIO.PUD_DOWN) # initialise temperature sensors sensorArray = DS18B20() count = sensorArray.device_count() # Create display instance on default I2C address (0x70) and bus number. display = BicolorMatrix8x8.BicolorMatrix8x8() display.begin() # Clear the display buffer. display.clear() tSleep = 1 tSleep_main = 5 print 'CTRL-C to stop' # Sourire image_smile = Image.new('RGB', (8, 8)) draw_smile = ImageDraw.Draw(image_smile)
mqttc.will_set("system/connectionstatus/raspberrypi2", payload="OFF", qos=2, retain=True) # Connect to the MQTT server if debug: print("Connecting to MQTT server...") connect(mqttc) time.sleep(1) mqttc.loop_start() time.sleep(1) # test temperature sensors x = DS18B20() count = x.device_count() while True: i = 0 while i < count: print(x.tempC(i)) #post data to mqtt broker publish_message(msg=x.tempC(i)[0], mqtt_path='raspberrypi2/temp/' + x.tempC(i)[1], mqtt_qos=2, mqtt_retain=True) i += 1 time.sleep(60)
def create_temp_sensors(): sensors = [SpiTempSensor(0, 0)] for s in DS18B20.get_available_sensors(): sensors.append(DS18B20(s)) return sensors
import ConfigParser import paho.mqtt.client as mqtt from ds18b20 import DS18B20 delay = 30.0 dir = os.path.dirname(os.path.realpath(__file__)) config = ConfigParser.SafeConfigParser() config.read(dir + '/application.cfg') mqtt_broker = config.get('mqtt', 'broker') sensor_locations = {} sensors = {} for id, location in config.items('sensors'): sensor_locations[id] = location sensors[id] = DS18B20(id) mqtt_client = mqtt.Client() mqtt_client.connect(mqtt_broker) mqtt_client.loop_start() while True: for id in sensor_locations.keys(): location = sensor_locations[id] topic = "sensor/temperature/" + location temperature = sensors[id].read_fahrenheit() msg = json.dumps({ 'location': location, 'datetime': str(datetime.now()), 'type': 'temperature', 'value': temperature
deviceNames = ['Ruche01', 'Ruche02', 'Ruche03', 'Ruche04', 'Ruche05'] temperatureDeviceNames = ['Matrice01', 'Matice02', 'Matrice03', 'Matrice04', 'Matrice05'] #Matrice = la valeur moyenne de la température entre les 2 cadres connecting_time = time.time() + 10 if time.time() < connecting_time: #try connecting to AWS for 10 seconds myMQTTClient.connect() myMQTTClient.publish(topic, "connected", 0) print("MQTT Client connection success!") else: print("Error: Check your AWS details in the program") #create external temperature sensor variable exTemperatureSensor = DS18B20() #create internal temperature sensor variable inTemperatureSensor = 0 #PUT THE REAL FUNCTION HERE !! #Event Handler Callback Functions def BridgeAttached(e): attached = e.device print("Bridge %i Attached!" % (attached.getSerialNum())) def BridgeDetached(e): detached = e.device print("Bridge %i Detached!" % (detached.getSerialNum())) def BridgeError(e):
#!/usr/bin/env python # -*- coding: utf-8 -*- import cgi import cgitb import sqlite3 import Adafruit_DHT from ds18b20 import DS18B20 # setup GPIO-related variables hum_sensor = 22 hum_pin = 17 amb_sensor = DS18B20() # setup gauge limits Ambient_yellowTo = 5 Ambient_redFrom = 25 Fridge_yellowTo = 9 Fridge_redFrom = 14 Humidity_yellowTo = 50 Humidity_redFrom = 75 Outside_yellowTo = 2 Outside_redFrom = 35 # unicode degrees symbol degsym ='\u00b0' # enable tracebacks of exceptions cgitb.enable() # grab the current, most recent sensor readings from the database def get_latest_readings():
def __init__(self, event): Thread.__init__(self) self.stopped = event self.ds18b20 = DS18B20()
reader = csv.reader(config_file) config = {rows[0]: rows[1] for rows in reader} logger.debug(config) atlas_ph_id = None atlas_ec_id = None try: atlas_ph_id = config["atlas_ph_id"] atlas_ec_id = config["atlas_ec_id"] logger.debug("Atlas pH ID is: {}, Atlas EC ID is: {}".format( atlas_ph_id, atlas_ec_id)) except: logger.error("Unable to parse config file") atlas_ph_1 = AtlasPh(atlas_ph_id) atlas_ec_1 = AtlasEc(atlas_ec_id) ds18b20_1 = DS18B20() grove_o2_1 = GroveO2() while True: mhz16_1.poll() mhz16_1.transmitToMemcache(shared) am2315_1.poll() am2315_1.transmitToMemcache(shared) atlas_ph_1.poll() atlas_ph_1.transmitToMemcache(shared) atlas_ec_1.poll() atlas_ec_1.transmitToMemcache(shared)
from ds18b20 import DS18B20 import gspread from oauth2client.service_account import ServiceAccountCredentials # use creds to create a client to interact with the Google Drive API scope = [ 'https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive' ] creds = ServiceAccountCredentials.from_json_keyfile_name( 'client_secret.json', scope) client = gspread.authorize(creds) # DS18B20 probes = DS18B20() probe_count = probes.device_count() # Constants global_offset = 2 # 2 Degree change, then we push changes. """ So the old temperature is 18C and the new temperature is 21C, offset is 2, this would return true, and so should now post into the Google Sheet. """ def rangeCheck(old_number, offset, new_number): # Thanks @Eladkay, for this return not new_number <= (old_number + offset) and new_number > ( old_number - offset) """ Get the last temperatures posting, compare to the current temperatures. If they exceed offsets, send an update to the google sheet """
os.path.abspath(os.path.join(os.getcwd(), os.pardir)) + "/config/temperaturesensors.json") as json_temperaturesensors: temperaturesensors = json.load(json_temperaturesensors) except: print "Temperature Sensor config file not found." #Log temperatures to CSV. while True: try: data = [] currentDT = datetime.datetime.now() data.append(currentDT.strftime("%m-%d-%Y %I:%M:%S %p")) for temperaturesensor in temperaturesensors: data.append( str("%.1f" % ( DS18B20(str(temperaturesensor['address'])).get_temperature( DS18B20.DEGREES_F) + temperaturesensor['temperaturecorrection']))) file = open( os.path.abspath( os.path.join(os.getcwd(), os.pardir) + "/static/temp.txt"), "a") write = str((data[0], data[1], data[2])) + "\n" write = write.translate(None, "(')") file.write(write) file.close() print data time.sleep(30) except KeyboardInterrupt: quit() except: print "Error logging temperatures."
def ds18b20_init(): # initialise temperature sensors sensorArray = DS18B20()
def run(self): #Create this function to run #bring in global variables global weightTop global weightMid global weightBot global dryMatter global initialSampleWeight global targetWeight dryMatterPercent = dryMatter/initialSampleWeight initialMoisturePercent = 1-dryMatterPercent #ui2.show() count = 0 #In this case creating a counter while True: #While counter is less than 100 (edited to While True, from count < 100) #time.sleep(.5) #Wait half a second #print("Increasing") #Print this for debugging count += 1 #increment count ui2.updateLED(count) #Update the LED by calling this method of the ControlWindow Class x = DS18B20() counter=x.device_count() #count number of temperature sensors i = 0 templist = [] #create list to save temp data while i < counter: temp_temp = x.tempC(i) #read temp data of first sensor templist.append(temp_temp) i += 1 top_temp_f = (templist[0] * 9.0 / 5.0 + 32.0) * 0.98945 bot_temp_f = (templist[1] * 9.0 / 5.0 + 32.0) * 0.96945 ui2.updateTopTemp(top_temp_f) #updates temperature sensor display ui2.updateBotTemp(bot_temp_f) vRatioTop = wd.main0() #calls main0 of other script, to import voltage ratio reading #print(vRatioTop) weightTop = -5.10209e5*vRatioTop-zeroTop #calculates weight based on calibration vRatioMid = wd.main1() #calls main1 of other script, to import voltage ratio reading #print(vRatioMid) weightMid = -5.002223e5*vRatioMid-zeroMid #calculates weight based on calibration vRatioBot = wd.main2() #calls main0 of other script, to import voltage ratio reading #print(vRatioBot) weightBot = -4.9078e5*vRatioBot-zeroBot #calculates weight based on calibration ui2.updateTopWeight(weightTop) #updates weight display box ui2.updateMiddleWeight(weightMid) #updates weight display box ui2.updateBottomWeight(weightBot) #updates weight display box moistureTop = -100*(((dryMatter*initialWeightTop)/(weightTop*initialSampleWeight))-1) #DO MOISTURE CALC HERE moistureMid = -100*(((dryMatter*initialWeightMid)/(weightMid*initialSampleWeight))-1) #DO MOISTURE CALC HERE moistureBot = -100*(((dryMatter*initialWeightBot)/(weightBot*initialSampleWeight))-1) #DO MOISTURE CALC HERE ui2.updateTopMoistureDisplay(moistureTop) #updates moisture display box ui2.updateMiddleMoistureDisplay(moistureMid) #updates moisture display box ui2.updateBottomMoistureDisplay(moistureBot) #updates moisture display box # print(EStopTemp) ui2.show() app.processEvents() #print(started) if started == True: GPIO.output(6, GPIO.HIGH) #else: #GPIO.output(6, GPIO.LOW) #if moistureTop < 8: # shutoff() if moistureTop < targetPercent or moistureMid < targetPercent or moistureBot < targetPercent: shutoff() #Test of controlling power relay based on temperature if top_temp_f > EStopTemp or bot_temp_f > EStopTemp: shutoff()
outlet_num = int(payload[6]) if (len(payload) == 7) else 'all' relays.off(outlet_num) print('O1: {}, O2: {}, O3: {}, O4: {}'.format( relays.receive_info_states())) #--------------------------------MAIN CODE------------------------------- client = MQTTClient(ADAFRUIT_IO['USERNAME'], ADAFRUIT_IO['KEY']) client.on_connect = connected client.on_disconnect = disconnected client.on_message = message client.connect() relays = four_relays(outlet_pins, outlet_names, outlet_types) ds = DS18B20('f', 2) num_ds = ds.device_count() print('Number of DS18B20 sensors detected: {}'.format(num_ds)) last = 0 print('Publishing a new message every 10 seconds (press Ctrl-C to quit)...') while True: #sensor_values = (ds.temp(), bmp.pressure(), bmp.altitude('ft'), bh.light('lux'), pir.motion(t_last_motion)) client.loop() if (time.time() - last) >= sample_rate: room_temp = ds.temp() print('Publishing {0:.2f}F to RoomTemp feed.'.format(room_temp)) client.publish(PUB_FEED, room_temp) last = time.time() #------------------------------------------------------------------------
GPIO.setup(FLOW_SENSOR1, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(FLOW_SENSOR2, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(debug_pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(maintenance_pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(FILTER_SENSOR, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(filter_alert_LED, GPIO.OUT) GPIO.setup(active_running_led, GPIO.OUT, initial=1) # these two add the listener threads to th GPIO for the flow meter - they will count the pulses in the background # while the program runs, and then will update the counter(s) for readout on the interval GPIO.add_event_detect(FLOW_SENSOR1, GPIO.FALLING, callback=Flow_meter1) GPIO.add_event_detect(FLOW_SENSOR2, GPIO.FALLING, callback=Flow_meter2) # Initialize temp sensor # this uses 1-wire and is connected to GPIO4 (although i do not think this matters?) temp_sensor = DS18B20() # initialize MQTT for sending to the home hub and spcify the variables for holding messages broker_address = "192.168.68.115" client = mqtt.Client("Filter_Monitor") #create new instance def Collect_Flow_Data(): # Get current LPM from flow meters: flow1 = (count1 / 7.5) flow2 = (count2 / 7.5) lcd.cursor_pos = (0, 0) lcd.write_string('Flow 1 {0:.2f} LPM'.format(flow1)) lcd.cursor_pos = (1, 0) lcd.write_string('Flow 2 {0:.2f} LPM'.format(flow2)) data0 = '{{\"Unit\":\"Filter\",\"Sensor\":\"Filter_Flow\",\"Values\":{{\"Flow1\":\"{0:.2f}\",\"Flow2\":\"{1:.2f}\"}}}}'.format(