def read(self): try: sht_sensor = Sht(self.clock_pin, self.pin, voltage=self.voltage) self._temperature = sht_sensor.read_t() self._humidity = sht_sensor.read_rh() except: return None
#!/usr/bin/python import datetime import time from sht_sensor import Sht sht = Sht(4, 17) for x in range(0, 10): temperature = sht.read_t() humidity = sht.read_rh(temperature) dew_point = sht.read_dew_point(temperature, humidity) print "Temperature: %s" % temperature print "Humidity: %s" % humidity print "Dew Point: " % dew_point time.sleep(2)
#!/usr/bin/python from sht_sensor import Sht sht = Sht(4, 17) print "temp:", sht.read_t() print "rh:", sht.read_rh()
BOARD_MODE = gpio.BCM # GPIO board mode PIN_DHT = 17 # Pin für Temp/Hum Sensor PIN_HEATER = 27 # Pin für Heizkabel PIN_COOL = 22 # Pin für Kühlschrankkompressor PIN_FAN = 18 # Pin für Umluftventilator PIN_FAN1 = 23 # Pin für Austauschlüfter PIN_HUM = 24 # Pin für Luftbefeuchter sht = Sht(21, 20) VERBOSE = True #RRD-Tool konfiguration dbname = 'dht22' # Name fuer Grafiken etc filename = dbname + '.rrd' # Dateinamen mit Endung steps = 10 # Zeitintervall fuer die Messung in Sekunden i = 0 z = 0 # Funktionen ############################################################################################################ ######################################################################################################################## def goodbye(): cleanup()
"""Specific module to calculate relative humidity with the sensor""" import json from sht_sensor import Sht with open('sensorConfig.json') as json_file: FILE_DATA = json.load(json_file) SHT = Sht(FILE_DATA["sht sensor pin numbers 1"], FILE_DATA["sht sensor pin numbers 2"]) class RelativeHumidity(object): """Relative Humidity Sensor GPIO pin 11 and 13""" def __init__(self): """""" def relative_humidity(self): """Specific method to get relative humidity in %RH""" return SHT.read_rh()
class SHT1x7xSensor(AbstractInput): """ A sensor support class that measures the SHT1x7x's humidity and temperature and calculates the dew point """ def __init__(self, input_dev, testing=False): super(SHT1x7xSensor, self).__init__() self.logger = logging.getLogger("mycodo.inputs.sht1x_7x") self._dew_point = None self._humidity = None self._temperature = None if not testing: from sht_sensor import Sht from sht_sensor import ShtVDDLevel self.logger = logging.getLogger( "mycodo.inputs.sht1x_7x_{id}".format(id=input_dev.id)) self.location = int(input_dev.location) self.clock_pin = input_dev.clock_pin self.convert_to_unit = input_dev.convert_to_unit sht_sensor_vdd_value = { 2.5: ShtVDDLevel.vdd_2_5, 3.0: ShtVDDLevel.vdd_3, 3.5: ShtVDDLevel.vdd_3_5, 4.0: ShtVDDLevel.vdd_4, 5.0: ShtVDDLevel.vdd_5 } self.sht_voltage = sht_sensor_vdd_value[round( float(input_dev.sht_voltage), 1)] self.sht_sensor = Sht(self.clock_pin, self.location, voltage=self.sht_voltage) def __repr__(self): """ Representation of object """ return "<{cls}(dewpoint={dpt})(humidity={hum})(temperature={temp})>".format( cls=type(self).__name__, dpt="{0:.2f}".format(self._dew_point), hum="{0:.2f}".format(self._humidity), temp="{0:.2f}".format(self._temperature)) def __str__(self): """ Return measurement information """ return "Dew Point: {dpt}, Humidity: {hum}, Temperature: {temp}".format( dpt="{0:.2f}".format(self._dew_point), hum="{0:.2f}".format(self._humidity), temp="{0:.2f}".format(self._temperature)) def __iter__(self): # must return an iterator """ SHT1x7xSensor iterates through live measurement readings """ return self def next(self): """ Get next measurement reading """ if self.read(): # raised an error raise StopIteration # required return dict(dewpoint=float('{0:.2f}'.format(self._dew_point)), humidity=float('{0:.2f}'.format(self._humidity)), temperature=float('{0:.2f}'.format(self._temperature))) @property def dew_point(self): """ SHT1x7x dew point in Celsius """ if not self._dew_point: # update if needed self.read() return self._dew_point @property def humidity(self): """ SHT1x7x relative humidity in percent """ if not self._humidity: # update if needed self.read() return self._humidity @property def temperature(self): """ SHT1x7x temperature in Celsius """ if self._temperature is None: # update if needed self.read() return self._temperature def get_measurement(self): """ Gets the humidity and temperature """ self._dew_point = None self._humidity = None self._temperature = None temperature = convert_units('temperature', 'celsius', self.convert_to_unit, self.sht_sensor.read_t()) humidity = self.sht_sensor.read_rh() dew_point = self.sht_sensor.read_dew_point(temperature, humidity) dew_point = convert_units('dewpoint', 'celsius', self.convert_to_unit, dew_point) return dew_point, humidity, temperature def read(self): """ Takes a reading from the SHT1x7x and updates the self.dew_point, self._humidity, and self._temperature values :returns: None on success or 1 on error """ try: (self._dew_point, self._humidity, self._temperature) = self.get_measurement() if self._dew_point is not None: return # success - no errors except Exception as e: self.logger.exception( "{cls} raised an exception when taking a reading: " "{err}".format(cls=type(self).__name__, err=e)) return 1
#!/usr/bin/env python # -*- coding: utf-8 -*- # Uso CRONTAB -e per editare ed eseguire il programma import RPi.GPIO as GPIO # access to GPIO must be through root import time import sys import datetime #from sht_sensor import Sht from sht_sensor import Sht sht = Sht(21, 17) # sensore della Sensitron SHT75 LATCH = 11 # CS GP11 pin 23 CLK = 12 # CLOCK GP12 pin 32 dataBit = 7 # DIN GP07 pin 26 #Definiamo il sistema di riferimento dei pin. Con GPIO.BCM usiamo i numeri GPIO dei pin e non # il numero dei pin. # Ad esempio con GPIO.setmode(GPIO.BCM) per riferirci al pin GPIO17, usiamo 17 (e non 11). #Per indicare che ci si riferisce al numero del pin, si usa GPIO.setmode(GPIO.BOARD) GPIO.setmode(GPIO.BCM) #usiamo la numerazione BCM GPIO.setwarnings(False) GPIO.setup(LATCH, GPIO.OUT) # P0 11 GPIO.setup(CLK, GPIO.OUT) # P1 12 GPIO.setup(dataBit, GPIO.OUT) # P7 7 #------------------------------------------------------------------------------- GPIO.output(LATCH, 0) # Setup IO GPIO.output(CLK, 0)
def print_serial(self, buffer): sht = Sht(3, 2) s = datetime.datetime.now() #self.n+=1 chksum = self.chksum_cal(buffer) data = self.unpack_data(buffer) a = data[self.DUST_PM1_0_CF1] b = data[self.DUST_PM1_0_ATM] c = data[self.DUST_PM2_5_CF1] d = data[self.DUST_PM2_5_ATM] e = data[self.DUST_PM10_0_CF1] f = data[self.DUST_PM10_0_ATM] g = data[self.DUST_AIR_0_3] h = data[self.DUST_AIR_0_5] i = data[self.DUST_AIR_1_0] j = data[self.DUST_AIR_2_5] k = data[self.DUST_AIR_5_0] l = data[self.DUST_AIR_10_0] #print(s,a,b,c,d,e,f,g,h,i,j,k,l) self.input_parameter = [ d, round(sht.read_t(), 3), round(sht.read_rh(), 3) ] self.input_parameter = np.array([self.input_parameter]) self.input_parameter = scaler.transform(self.input_parameter) # self.t+=[[model.predict(self.input_parameter),d,round(sht.read_t(),3),round(sht.read_rh(),3)]] self.ai = float(model.predict(self.input_parameter)) #print(s,a,b,c,round(sht.read_t(),3),round(sht.read_rh(),3)) # print (data[self.DUST_PM1_0_CF1], data[self.DUST_PM1_0_ATM]) # print (data[self.DUST_PM2_5_CF1], data[self.DUST_PM2_5_ATM]) # print (data[self.DUST_PM10_0_CF1], data[self.DUST_PM10_0_ATM]) # print ("0.3um in 0.1L of air : %s" % (data[self.DUST_AIR_0_3])) # print ("0.5um in 0.1L of air : %s" % (data[self.DUST_AIR_0_5])) # print ("1.0um in 0.1L of air : %s" % (data[self.DUST_AIR_1_0])) # print ("2.5um in 0.1L of air : %s" % (data[self.DUST_AIR_2_5])) # print ("5.0um in 0.1L of air : %s" % (data[self.DUST_AIR_5_0])) # print ("10.0um in 0.1L of air : %s" % (data[self.DUST_AIR_10_0])) # print ("Reserved F : %s | Reserved B : %s" % (data[self.RESERVEDF],data[self.RESERVEDB])) # print ("CHKSUM : %s | read CHKSUM : %s | CHKSUM result : %s" % (chksum, data[self.CHECKSUM], chksum == data[self.CHECKSUM])) # print ("============================================================================") self.n += 1 try: ser6.write(serial.to_bytes([0x02, 0x52, 0x00, 0x00, 0x03])) send1 = "0252000003" #send1=int(send1,16) #send1=send1.encode('utf-8') #byteToRead1 = ser6.inWaiting() s = ser6.readline() s = str(s) s = s.split(',') print(s) # gas=s[1]+","+s[2]+","+s[3]+","+s[4]+","+s[6]+","+s[7]+model.predict(self.input_parameter)+","+d+","+sht.read_t()+","+sht.read_rh() # print(gas) time_now = datetime.datetime.now() self.send = str( "AI PM 2.5 :" + str(round(self.ai, 2)) ) + ", Raw PM 2.5 :" + str(round(d, 2)) + ", Temp :" + str( round(sht.read_t(), 2)) + ", Humidity :" + str( round(sht.read_rh(), 2)) + ", CO :" + str( round(float(s[1]) / 1.2, 2) ) + ", SO2 :" + s[2] + ", H2S :" + s[3] + ", VOC: " + str( round(float(s[4]) / 3.5, 2)) + ", NO2: " + s[6] + ", O3: " + s[7] + "\r\n" self.send2 = str(time_now) + " , " + str( "AI PM 2.5 :" + str(round(self.ai, 2)) ) + ", Raw PM 2.5 :" + str(round(d, 2)) + ", Temp :" + str( round(sht.read_t(), 2)) + ", Humidity :" + str( round(sht.read_rh(), 2)) + ", CO :" + str( round(float(s[1]) / 1.2, 2) ) + ", SO2 :" + s[2] + ", H2S :" + s[3] + ", VOC: " + str( round(float(s[4]) / 3.5, 2)) + ", NO2: " + s[6] + ", O3: " + s[7] #str(float(s[4])/0.01+float(s[7])) self.send = self.send.encode('utf-8') #time.sleep(10) ser.write(self.send) print(time_now) # ser.write(s) #ser.write(self.send) #print(self.send) #print(ser6.isOpen()) self.t += [[str(self.send2)]] self.n += 1 ser6.write(serial.to_bytes([0x02, 0x53, 0x00, 0x00, 0x03])) except: print('connect error \n') if self.n == 2: print("it's start") # if self.n==5: # print(self.n) # df=pd.DataFrame(self.t) # path="/home/mems/Desktop/test/"+datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")+".csv" # df.to_csv(path) # print(self.n,"seconds _and save file") if self.n % 100 == 0: #print(self.n) df = pd.DataFrame(self.t) path = "/home/omni/Desktop/test2/" + datetime.datetime.now( ).strftime("%Y-%m-%d-%H-%M-%S") + ".csv" df.to_csv(path) #print(self.n,"seconds _and save file") self.t = []
def __init__(self, name, data, clock): self.name = name self.sht = Sht(data, clock, voltage="5V")
sht_vcc_pin = 5 sht_data_pin = 13 sht_sck_pin = 6 ir_pin_out = 23 # make sure sht15 sclk is set to low -- is required before power up wiringpi.digitalWrite(sht_sck_pin, 0) # power cycle sht_vcc_pin just in case wiringpi.digitalWrite(sht_vcc_pin, 0) sleep(3) # open 3.3v power pin to power up sht15 temp and humidity sensor... using phyiscal pin values (no "_g") wiringpi.pinMode(sht_vcc_pin, 1) wiringpi.digitalWrite(sht_vcc_pin, 1) # identify the SHT15's "sck" and "data" pins (using GPIO numbering, i..e the "_g" values), and VDD input voltage sht = Sht(sht_sck_pin, sht_data_pin, voltage='3.5V') # print initial f = open(FILENAME, "a") f.write("NA, NA, NA,NA\n") f.close() # loop that takes exactly 1 second to execute i = 0 while True: if wiringpi.digitalRead(ir_pin_out) == 1: dt = datetime.datetime.now() while True: i += 1 # Read SHT temp and RH dt_clk = datetime.datetime.now()
# Sends temperature and humidity data to Thingspeak from a SHT sensor connected to Raspberry # Requires sht-sensor library to be installed # Sends data in every 10 mins: # crontab -e # */10 * * * * /usr/bin/python /home/pi/sht_thingspeak.py # The connections are SCK pin: GPIO 21, DATA pin: GPIO 17 # tamasharasztosi, 2018 import sys import time import RPi.GPIO as GPIO from time import sleep from sht_sensor import Sht import urllib2 myAPI = "FILL_WITH_YOUR_API" sht = Sht(21, 18) # SCK pin: GPIO 21, DATA pin: GPIO 17 print 'Temperature', sht.read_t() print 'Relative Humidity', sht.read_rh() baseURL = 'https://api.thingspeak.com/update?api_key=FILL_WITH_YOUR_API' urllib2.urlopen(baseURL + "&field1=%s&field2=%s" % (sht.read_t(), sht.read_rh())).read()