def run(self): while True: now = datetime.datetime.now() time1 = now.strftime("%d %B %Y at %H:%M:%S") with SHT1x(18, 23, gpio_mode=GPIO.BCM) as sensor: config = { "apiKey": "Enter your api key here", "authDomain": "Enter your auth domain here", "databaseURL": "Enter database URL here", "projectId": "Enter Project ID", "storageBucket": "Enter storage bucket", "messagingSenderId": "Enter ms_id" } firebase = pyrebase.initialize_app(config) auth = firebase.auth() db = firebase.database() user = auth.sign_in_with_email_and_password( userEmail, userPass) temp = sensor.read_temperature() hum = sensor.read_humidity(temp) dew1 = sensor.calculate_dew_point(temp, hum) data = { 'Time Batch': time1, 'Temperature': temp, 'Humidity': hum, 'Dew Point': dew1 } result = db.child("pol2").child("SHT10").push( data, user['idToken']) print(str(result)) self.signal.emit() sleep(5) QApplication.processEvents()
def sensor_sensing(): # 개발용 - 온습도 현제 시간으로 # now = datetime.datetime.now() t = rh = None with SHT1x(DATA_PIN, SCK_PIN, gpio_mode=GPIO.BCM) as sensor: t = sensor.read_temperature() rh = sensor.read_humidity(t) return [t, rh]
def test_sht1x(DATA_PIN, SCK_PIN): with SHT1x(DATA_PIN, SCK_PIN, gpio_mode=GPIO.BOARD) as sensor: temp = sensor.read_temperature() humidity = sensor.read_humidity(temp) sensor.calculate_dew_point(temp, humidity) print(temp,humidity) return temp, humidity sleep(2) print('Test complete.\n')
def sht_indoor_sensor(in_temp_f, in_temp_c, in_hum, verb): #Get readings from indoor SHT1 sensor with SHT1x(24, 23, gpio_mode=GPIO.BCM) as sensor: in_temp_c = sensor.read_temperature() in_temp_f = sensor.read_temperature() in_hum = sensor.read_humidity(in_temp_c) sensor.calculate_dew_point(in_temp_c, in_hum) in_temp_f = c_to_f(in_temp_f) if verb: print('Indoor readings:\n', sensor) return in_temp_f, in_temp_c, in_hum
def sht_outdoor_sensor(out_temp_f, out_temp_c, out_hum, verb): #Get readings from outdoor SHT1 Sensor with SHT1x(22, 27, gpio_mode=GPIO.BCM) as sensor: out_temp_c = sensor.read_temperature() out_temp_f = sensor.read_temperature() out_hum = sensor.read_humidity(out_temp_c) sensor.calculate_dew_point(out_temp_c, out_hum) out_temp_f = c_to_f(out_temp_f) if verb: print('Outdoor readings:\n', sensor) return out_temp_f, out_temp_c, out_hum
def read_sensor(data_pin, clock_pin): """ Reads sensor values and returns tuple of (temperature, humidity, dew_point) """ with SHT1x(data_pin, clock_pin, gpio_mode=GPIO.BCM) as sensor: temperature = sensor.read_temperature() humidity = sensor.read_humidity(temperature) dew_point = sensor.calculate_dew_point(temperature, humidity) # print(sensor) temperature = temperature * 9 / 5.0 + 32 dew_point = dew_point * 9 / 5.0 + 32 return (temperature, humidity, dew_point)
def get_soil_sensor_dic(): with SHT1x(DATA_PIN, SCK_PIN, gpio_mode=GPIO.BCM) as sensor: logger.setLevel(LOG_LEVEL) temp = sensor.read_temperature() humidity = sensor.read_humidity(temp) dew_point = sensor.calculate_dew_point(temp, humidity) # print(sensor) now = get_now_timestamp() out_dic = { COL_TEMP: temp, COL_HUMIDITY: humidity, COL_DEW_POINT: dew_point, COL_DT_SECS: timestamp2unix(now) } return out_dic
def read_and_save_data(): while True: with SHT1x(data_pin=DATA_PIN, sck_pin=SCX_PIN, gpio_mode=GPIO.BCM) as sensor: temperature_readings = [] humidity_readings = [] for reading_num in range(NUM_OF_READINGS): temperature_readings.append(sensor.read_temperature()) humidity_readings.append(sensor.read_humidity()) time.sleep(1) redis_conn = get_redis_connection() save_readings(redis_conn, statistics.median_grouped(temperature_readings), statistics.median_grouped(humidity_readings)) time.sleep(READINGS_INTERVAL)
def finished(self): with SHT1x(18, 23, gpio_mode=GPIO.BCM) as sensor: temp = sensor.read_temperature() hum = sensor.read_humidity(temp) dew1 = sensor.calculate_dew_point(temp, hum) now = datetime.datetime.now() time1 = now.strftime("%d %B %Y at %H:%M:%S") self.textEdit.append( str(time1) + " , " + str(temp) + "°C, " + str(hum) + "%, " + str(dew1) + "°C \n") self.textEdit.moveCursor(QtGui.QTextCursor.End) self.lineEdit_5.setText(str(time1)) self.lineEdit_6.setText(str(temp) + "°C") self.lineEdit_10.setText(str(hum) + "%") self.lineEdit_11.setText(str(dew1) + "°C")
def readTempIn(): print("read tempIn") try: with SHT1x(18, 23, gpio_mode=GPIO.BCM) as sensor: tempIn = sensor.read_temperature() humidityIn = sensor.read_humidity(tempIn) newData[2] = (int(tempIn * 10)) / 10 newData[3] = int(humidityIn) if oldData[2] != newData[2]: oldData[2] = newData[2] if oldData[3] != newData[3]: oldData[3] = newData[3] except: print("error SHT read temp") finally: print("done ReadTempIn")
def data_Transmitting(self): illum = self.analog_read(0) time.sleep(1) try : sensor = SHT1x(26, 20, gpio_mode=GPIO.BCM) temp, humi = self.i2c_read(sensor, "all") finally: print("gpio clean up") GPIO.cleanup() self.db = pymysql.connect(host=self.url, port=3306, user=self.id, passwd=self.password, db=self.dbName, charset='utf8') self.cursor = self.db.cursor() sql = "INSERT INTO `sensor_data` (`temp`, `humi`, `illum`, `time`) VALUES ('" + str(temp) + "', '" + str(humi) + "', '" + str(illum) + "', CURRENT_TIMESTAMP);" print(sql) self.cursor.execute(sql) self.db.commit() self.db.close()
def run(self, path): path += '/' dev = AtomDevice(path + 'rpi.ini', path + 'logger.json') info = dev.scan_network(10000) dev.update(info) #if dev.update(info): # dev.register() logger = dev.get_logger() with SHT1x(13, 11) as s: while True: try: t = s.read_temperature() h = s.read_humidity(t) logger.info('Temperature: %f, Humidity: %f', t, h) sleep(1) except SHT1xError as e: logger.error(e)
from pi_sht1x import SHT1x import RPi.GPIO as GPIO with SHT1x(6, 12, gpio_mode=GPIO.BCM) as sensor: temp = sensor.read_temperature() humidity = sensor.read_humidity(temp) sensor.calculate_dew_point(temp, humidity) print(sensor)
def __init__(self): self._setup_config() try: mqttServer = self.config_object.get("SERVER_CONFIG", "MQTT_SERVER", fallback="127.0.0.1") mqttPort = self.config_object.getint("SERVER_CONFIG", "MQTT_PORT", fallback=1883) mqttTopic = self.config_object.get("SERVER_CONFIG", "MQTT_TOPIC", fallback="home/plant") client_keepalive = self.config_object.getint("SERVER_CONFIG", "CLIENT_KEEPALIVE", fallback=60) mqttUseUsernamePWAuth = self.config_object.getboolean( "SERVER_CONFIG", "MQTT_USE_USERNAME_PW_AUTH", fallback=False) if (mqttUseUsernamePWAuth): mqttUsername = self.config_object.get("SERVER_CONFIG", "MQTT_USERNAME", fallback="raspberrySoil") mqttPW = self.config_object.get("SERVER_CONFIG", "MQTT_PASSWORD") dataGatheringInterval = self.config_object.getint( "GENERAL_CONFIG", "DATA_GATHERING_INTERVAL", fallback=5) writeToCSV = self.config_object.getboolean("GENERAL_CONFIG", "WRITE_TO_CSV_FILE", fallback=False) verboseOutput = self.config_object.getboolean("GENERAL_CONFIG", "VERBOSE_OUTPUT", fallback=False) useRelay = self.config_object.getboolean("GENERAL_CONFIG", "USE_RELAY", fallback=False) humidityMinThreshold = self.config_object.getfloat( "GENERAL_CONFIG", "RELAY_HUMIDITY_MIN_THRESHOLD", fallback=0.0) humidityMaxThreshold = self.config_object.getfloat( "GENERAL_CONFIG", "RELAY_HUMIDITY_MAX_THRESHOLD", fallback=50.0) data_pin = self.config_object.getint("GPIO_CONFIG", "DATA_PIN", fallback=24) sck_pin = self.config_object.getint("GPIO_CONFIG", "SCK_PIN", fallback=23) self.relay_pin = self.config_object.getint("GPIO_CONFIG", "RELAY_PIN", fallback=18) except KeyError as kError: raise Exception( colored( "Configuration Error: Key {0} not found in config file.". format(kError), 'red')) if mqttServer and mqttTopic: print( colored("-------------------------------------------------", 'cyan')) print(colored("Rasperry Soil Sensor Data Publisher", 'magenta')) print( colored("-------------------------------------------------", 'cyan')) print(("[i] Using MQTT server " + colored("{}", 'yellow') + " on port " + colored("{}", 'yellow')).format( mqttServer, mqttPort)) print("[i] Channel: " + colored("{}", 'yellow').format(mqttTopic)) print("[i] Using user: "******"{}", 'yellow').format(mqttUsername)) print() client = mqttClient.Client() if (mqttUseUsernamePWAuth): client.username_pw_set(mqttUsername, mqttPW) client.on_connect = self._on_connect client.on_message = self._on_message client.connect(mqttServer, mqttPort, client_keepalive) GPIO.setmode(GPIO.BCM) GPIO.setup(self.relay_pin, GPIO.OUT) with SHT1x(data_pin, sck_pin, gpio_mode=GPIO.BCM) as sensor: if (writeToCSV): fields = ['Temp', 'Humidity'] filename = "measurements.csv" csvfile = open(filename, 'w') try: csvwriter = csv.writer(csvfile, delimiter=';') csvwriter.writerow(fields) finally: csvfile.close() try: print( colored("Sensor is collecting and sending data...", 'green')) while 1: if self.debug: temp = 12.65 + random.randint(1, 18) humidity = 35.102 + random.randint(1, 10) else: temp = sensor.read_temperature() humidity = sensor.read_humidity(temp) #sensor.calculate_dew_point(temp, humidity) jsonData = json.dumps({ "temperature": temp, "humidity": humidity, "relay_is_active": self.relay_is_active }) if (verboseOutput): print( self.get_formatted_current_datetime_string() + " " + jsonData) if (useRelay): if (humidity >= humidityMinThreshold and humidity <= humidityMaxThreshold): if (not self.relay_is_active): GPIO.output(self.relay_pin, GPIO.HIGH) # activate relay self.relay_is_active = True self.relayStartTime = datetime.now() self.relayCurrentTime = self.relayStartTime print( self. get_formatted_current_datetime_string( ) + " " + colored("Relay set active...", 'green') ) else: if (self.relay_is_active): self._stop_relay(log=True) client.publish(mqttTopic, jsonData) # MQTT publish if (writeToCSV): with open(filename, 'a+') as csvfile: csvwriter = csv.writer(csvfile, delimiter=';') fields = [temp, humidity] csvwriter.writerow(fields) sleep(dataGatheringInterval) except (KeyboardInterrupt, SystemExit): print() print( colored("Received keyboard interrupt, quitting ...", 'red')) if (useRelay and self.relay_is_active): self._stop_relay(log=True) print("Closing connection..")
from time import sleep import RPi.GPIO as GPIO from pi_sht1x import SHT1x # With BCM the pin numbering should match the GPIO header. #gpio_mode = GPIO.BOARD gpio_mode = GPIO.BCM data_pin = 17 clock_pin = 14 with SHT1x(data_pin, clock_pin, gpio_mode=gpio_mode) as sensor: temp = sensor.read_temperature() humidity = sensor.read_humidity(temp) sensor.calculate_dew_point(temp, humidity) print(sensor)
def main(): print( 'Test: using default values: 3.5V, High resolution, no heater, otp_no_reload off, CRC checking enabled...' ) with SHT1x(DATA_PIN, SCK_PIN, gpio_mode=GPIO.BCM) as sensor: for i in range(5): temp = sensor.read_temperature() humidity = sensor.read_humidity(temp) sensor.calculate_dew_point(temp, humidity) print(sensor) sleep(2) print('Test complete.\n') print( 'Test: reading all measurements using GPIO.BCM mode, 3V, High resolution, heater off, otp_no_reload off, ' 'and CRC check on.') with SHT1x(DATA_PIN, SCK_PIN, gpio_mode=GPIO.BCM, vdd='3.5V', resolution='High', heater=False, otp_no_reload=False, crc_check=True) as sensor: for i in range(5): temp = sensor.read_temperature() humidity = sensor.read_humidity(temp) sensor.calculate_dew_point(temp, humidity) print(sensor) sleep(2) print('Test complete.\n') print( 'Test: read humidity without providing the temperature as an argument...' ) with SHT1x(DATA_PIN, SCK_PIN, gpio_mode=GPIO.BCM) as sensor: for i in range(5): sensor.read_humidity() print('Temperature: {0}°C [{1}°F]\nHumidity: {2}'.format( sensor.temperature_celsius, sensor.temperature_fahrenheit, sensor.humidity)) sleep(2) print('Test complete.\n') print( 'Test: calculate dew point without providing temperature and humidity as arguments...' ) with SHT1x(DATA_PIN, SCK_PIN, gpio_mode=GPIO.BCM) as sensor: for i in range(5): sensor.calculate_dew_point() print(sensor) sleep(2) print('Test complete.\n') print('Test: turn otp_no_reload on...') with SHT1x(DATA_PIN, SCK_PIN, gpio_mode=GPIO.BCM, otp_no_reload=True) as sensor: for i in range(5): temp = sensor.read_temperature() humidity = sensor.read_humidity(temp) sensor.calculate_dew_point(temp, humidity) print(sensor) sleep(2) print('Test complete.\n') print('Test: use low resolution...') with SHT1x(DATA_PIN, SCK_PIN, gpio_mode=GPIO.BCM, resolution='Low') as sensor: for i in range(5): temp = sensor.read_temperature() humidity = sensor.read_humidity(temp) sensor.calculate_dew_point(temp, humidity) print(sensor) sleep(2) print('Test complete.\n') print('Test: change resolution after object creation...') with SHT1x(DATA_PIN, SCK_PIN, gpio_mode=GPIO.BCM) as sensor: print('High resolution...') for i in range(5): temp = sensor.read_temperature() humidity = sensor.read_humidity(temp) sensor.calculate_dew_point(temp, humidity) print(sensor) sleep(2) print('Complete.\n') sensor.resolution = SHT1x.RESOLUTION['Low'] print('Low resolution...') for i in range(5): temp = sensor.read_temperature() humidity = sensor.read_humidity(temp) sensor.calculate_dew_point(temp, humidity) print(sensor) sleep(2) print('Test complete.\n') print('Test: Read the Status Register (default)...') with SHT1x(DATA_PIN, SCK_PIN, gpio_mode=GPIO.BCM) as sensor: status_register = sensor.read_status_register() print('Status Register: {0:08b}'.format(status_register)) print('Test complete.\n') print( 'Test: Read the Status Register (low resolution, otp_no_reload on)...') with SHT1x(DATA_PIN, SCK_PIN, gpio_mode=GPIO.BCM, resolution='Low', otp_no_reload=True) as sensor: status_register = sensor.read_status_register() print('Status Register: {0:08b}'.format(status_register)) print('Test complete.\n') print('Test: resetting the connection to the sensor...') with SHT1x(DATA_PIN, SCK_PIN, gpio_mode=GPIO.BCM) as sensor: sensor.reset_connection() sensor.read_temperature() print('Temperature: {0}°C [{1}°F]'.format( sensor.temperature_celsius, sensor.temperature_fahrenheit)) print('Test complete.\n') print('Test: performing a soft reset of the sensor...') with SHT1x(DATA_PIN, SCK_PIN, gpio_mode=GPIO.BCM, otp_no_reload=True) as sensor: sensor.soft_reset() status_register = sensor.read_status_register() print('Status Register: {0:08b}'.format(status_register)) sensor.read_temperature() print('Temperature: {0}°C [{1}°F]'.format( sensor.temperature_celsius, sensor.temperature_fahrenheit)) print('Test complete.\n') print('Test: resetting the status register...') with SHT1x(DATA_PIN, SCK_PIN, gpio_mode=GPIO.BCM, otp_no_reload=True) as sensor: sensor.reset_status_register() status_register = sensor.read_status_register() print('Status Register: {0:08b}'.format(status_register)) sensor.read_temperature() print('Temperature: {0}°C [{1}°F]'.format( sensor.temperature_celsius, sensor.temperature_fahrenheit)) print('Test complete.\n') print('Test: CRC disabled...') with SHT1x(DATA_PIN, SCK_PIN, gpio_mode=GPIO.BCM, vdd='3.5V', resolution='High', heater=False, otp_no_reload=False, crc_check=False) as sensor: for i in range(5): temp = sensor.read_temperature() humidity = sensor.read_humidity(temp) sensor.calculate_dew_point(temp, humidity) print(sensor) sleep(2) print('Test complete.\n')
def measure(self): with SHT1x(self.DATA, self.SCK, GPIO.BCM) as sensor: tem = sensor.read_temperature() hum = sensor.read_humidity(tem) return tem, hum
from time import sleep import RPi.GPIO as GPIO from pi_sht1x import SHT1x DATA_PIN = 18 SCK_PIN = 23 with SHT1x(DATA_PIN, SCK_PIN, gpio_mode=GPIO.BCM) as sensor: temp = sensor.read_temperature() humidity = sensor.read_humidity(temp) sensor.calculate_dew_point(temp, humidity) print (sensor) sleep(2)
def getUmi(): if IS_WINDOWS: return 35.555 with SHT1x(18, 23, gpio_mode=GPIO.BCM) as sensor: return sensor.read_humidity()
def main(): vdd_choices = Choices(['5V', '4V', '3.5V', '3V', '2.5V']) resolution_choices = Choices(['HIGH', 'LOW']) parser = argparse.ArgumentParser( description= 'Reads the temperature and relative humidity from the SHT1x series ' 'of sensors using the pi_sht1x library.') parser.add_argument('data_pin', type=int, metavar='data-pin', help='Data pin used to connect to the sensor.') parser.add_argument('sck_pin', type=int, metavar='sck-pin', help='SCK pin used to connect to the sensor.') parser.add_argument( '-g', '--gpio-mode', choices=['BCM', 'BOARD'], default='BCM', help= 'RPi.GPIO mode used, either GPIO.BOARD or GPIO.BCM. Defaults to GPIO.BCM.' ) parser.add_argument( '-v', '--vdd', choices=vdd_choices, default='3.5V', help='Voltage used to power the sensor. Defaults to 3.5V.') parser.add_argument( '-r', '--resolution', choices=resolution_choices, default='HIGH', help= 'Resolution used by the sensor, 14/12-bit or 12-8-bit. Defaults to High.' ) parser.add_argument( '-e', '--heater', action='store_true', help='Used to turn the internal heater on (used for calibration).') parser.add_argument( '-o', '--otp-no-reload', action='store_true', help= 'Used to enable OTP no reload, will save about 10ms per measurement.') parser.add_argument('-c', '--no-crc-check', action='store_false', help='Performs CRC checking.') parser.add_argument('-d', '--debug', action='store_true', help='Enable debug logging.') args = parser.parse_args() if args.debug: logger.setLevel(logging.DEBUG) mode = GPIO.BCM if args.gpio_mode.upper() == 'BCM' else GPIO.BOARD with SHT1x(args.data_pin, args.sck_pin, gpio_mode=mode, vdd=args.vdd, resolution=args.resolution, heater=args.heater, otp_no_reload=args.otp_no_reload, crc_check=args.no_crc_check, logger=logger) as sensor: for i in range(5): temp = sensor.read_temperature() humidity = sensor.read_humidity(temp) sensor.calculate_dew_point(temp, humidity) print(sensor) sleep(2)
def getTemp(): if IS_WINDOWS: return 27.777 with SHT1x(18, 23, gpio_mode=GPIO.BCM) as sensor: return sensor.read_temperature()
def getData(self): with SHT1x(DATA_PIN, SCK_PIN, gpio_mode=GPIO.BCM) as sensor: temp = sensor.read_temperature() humidity = sensor.read_humidity(temp) sensor.calculate_dew_point(temp, humidity) return temp,humidity
#Creating users #auth.create_user_with_email_and_password(email, password) #Verify Email #auth.send_email_verification(user['idToken']) #print(auth.get_account_info(user['idToken'])) #Reset Password #auth.send_password_reset_email(email) # Get a reference to the database service db = firebase.database() while True: with SHT1x(18, 23, gpio_mode=GPIO.BCM) as sensor: temp = sensor.read_temperature() hum = sensor.read_humidity(temp) dew1 = sensor.calculate_dew_point(temp, hum) #data to store data = { 'Time Batch': time1, 'Temperature': temp, 'Humidity': hum, 'Dew Point': dew1 } # Pass the user's idToken to the push method results = db.child("Pol1").child("Test").push(data, user['idToken']) print(
import datetime import time from time import strftime import sys import RPi.GPIO as GPIO from pi_sht1x import SHT1x DataPin = 24 SCKPin = 23 with SHT1x(DataPin, SCKPin, gpio_mode=GPIO.BCM) as sensor: tempSHT = sensor.read_temperature() humiSHT = sensor.read_humidity(tempSHT) #sensor.calculate_dew_point(tempSHT,humiSHT) f = open('/usr/share/webiopi/htdocs/ccc/txt/data_tempSHT.txt','a') data_entry2 = "{0},{1}\n".format(strftime("%Y-%m-%d %H:%M:%S"),"%.2f" % tempSHT) f.write(data_entry2) f.close() f = open('/usr/share/webiopi/htdocs/ccc/txt/data_humiSHT.txt','a') data_entry3 = "{0},{1}\n".format(strftime("%Y-%m-%d %H:%M:%S"),"%.2f" % humiSHT) f.write(data_entry3) f.close()