def test_barometric_pressure(): logging.info('Testing Barometric Pressure Sensor (BMP280)...') try: barometer = BMP280.BMP280() logging.info('Temp = %.2f *F', (barometer.read_temperature() * 1.8) + 32) logging.info('Pressure = %.2f Pa', barometer.read_pressure()) logging.info('Altitude = %.2f m', barometer.read_altitude()) logging.info('Sealevel Pressure = %.2f Pa', barometer.read_sealevel_pressure()) logging.info('Barometric Pressure Test was Successful (BMP280)') except Exception as exc: logging.error('Barometric Pressure Test Failed')
def test_barometric_pressure(self): # if self._i2cmux is None: # self.test_i2c_mux() # self._i2cmux.write_control_register(TCA9545_CONFIG_BUS0) logging.info('Testing Barometric Pressure Sensor (BMP280)...') try: self._barometer = BMP280.BMP280() logging.info('Temp = %.2f *F', (self._barometer.read_temperature() * 1.8) + 32) logging.info('Pressure = %.2f Pa', self._barometer.read_pressure()) logging.info('Altitude = %.2f m', self._barometer.read_altitude()) logging.info('Sealevel Pressure = %.2f Pa', self._barometer.read_sealevel_pressure()) logging.info('Barometric Pressure Test was Successful (BMP280)') except Exception as exc: logging.error('Barometric Pressure Test Failed')
def initializeSensors(self): # Instantiate GPS data retrieval mechanism try: self.agps_thread = AGPS3mechanism() self.agps_thread.stream_data() self.agps_thread.run_thread() except: print("Failed initializing GPS") pass self.sense = None self.pressureSensor = None try: self.sense = SenseHat() except: print("Failed initializing Sense Hat") pass try: self.pressureSensor = BMP280.BMP280() except: print("Failed initializing Pressure Sensor") pass
import schattenspeicher import Adafruit_BMP.BMP280 as BMP280 import RPi.GPIO as GPIO import time import datetime import board import busio import adafruit_ads1x15.ads1115 as ADS from adafruit_ads1x15.analog_in import AnalogIn # Create the I2C bus i2c = busio.I2C(board.SCL, board.SDA) # Create the ADC object using the I2C bus ads = ADS.ADS1115(i2c) GPIO.setmode(GPIO.BCM) tempSensor = BMP280.BMP280() # ### Initialisierungen i = 0 n = 0 zyklusGesamt = 0 zyklusWasser = 0 # Teilmenge von zyklusGesamt, Zyklen in welchen bewässert wurde LetzterWasserZyklus = 0 # Hilfswert für PlausiCheck plausiZaehler = 0 # Hilfswert für PlausiCheck PlausiCheck = 0 s = 0.0 moistureLevel_1 = 0.0 moistureLevel_2 = 0.0 opVoltage = 0.0 pumpenMessSpannung = 0.0 # sleep Werte können an sich problemlos angepasst werden, 1s default sleepSensor1 = 1 # Vor Analog-Spannung 1 einlesen sleepSensor2 = 1 # Vor Sensor-Versorgung 1 auf 0.0V
print("reading first 4 addresses") for x in range(0, 4): print("address = %i value = %i" % (x, ds3231.read_AT24C32_byte(x))) print("----------------- ") except IOError as e: # print "I/O error({0}): {1}".format(e.errno, e.strerror) config.DS3231_Present = False # do the AT24C32 eeprom ################ # BMP280 Setup - internal barometer try: bmp280 = BMP280.BMP280() config.BMP280_Present = True except IOError as e: print("BMP280 I/O error({0}): {1}".format(e.errno, e.strerror)) config.BMP280_Present = False ################ # HTU21DF Detection try: HTU21DFOut = subprocess.check_output(["htu21dflib/htu21dflib", "-l"]) config.HTU21DF_Present = True except: config.HTU21DF_Present = False ################ # OLED SSD_1306 Detection
def __init__(self, i2c_addr=0x76, dbhost="localhost", dbport=8086, dbname=None): self.sensor = BMP280.BMP280(address=i2c_addr) self.dbclient = influxdb.InfluxDBClient(dbhost, dbport, database=dbname)
#!/usr/bin/python #bmp280 import Adafruit_BMP.BMP280 as BMP280 sensor = BMP280.BMP280() tempBMP = sensor.read_temperature() pressureBMP = sensor.read_pressure() altitudeBMP = sensor.read_altitude() sealevelBMP = sensor.read_sealevel_pressure() sealevel = 1010.3 #AM2303 import Adafruit_DHT sensor = Adafruit_DHT.AM2302 pin = 17 humidityDHT, tempDHT = Adafruit_DHT.read_retry(sensor, pin) #Calcs import time from datetime import datetime from time import strftime, localtime from meteocalc import dew_point, heat_index tBMP = tempBMP * 9 / 5 + 32 tDHT = tempDHT * 9 / 5 + 32 hDHT = humidityDHT dpBMPc = dew_point(temperature=tempBMP, humidity=hDHT) hiBMPc = heat_index(temperature=tempBMP, humidity=hDHT) dpDHTc = dew_point(temperature=tempDHT, humidity=hDHT) hiDHTc = heat_index(temperature=tempDHT, humidity=hDHT) dpBMP = dpBMPc * 9 / 5 + 32 dpDHT = dpDHTc * 9 / 5 + 32
class GroveWeatherPi: # Load Devices weatherStation = SDL_Pi_WeatherRack.SDL_Pi_WeatherRack( anemometerPin, rainPin, 0, 0, SDL_MODE_I2C_ADS1015) ds3231 = SDL_DS3231.SDL_DS3231(1, 0x68) bmp280 = BMP280.BMP280() max44009 = MAX44009.MAX44009(1, 0x4a) display = Adafruit_SSD1306.SSD1306_128_64(rst=RST, i2c_address=0x3C) am2315 = AM2315(0x5c, "/dev/i2c-1") # initialize appropriate weather variables currentWindDirection = 0 currentWindDirectionVoltage = 0.0 rain60Minutes = 0.0 totalRain = 0 rainArray = [] lastRainReading = 0.0 def __init__(self): self.weatherStation.setWindMode(SDL_MODE_SAMPLE, 5.0) #self.ds3231.write_now() self.ds3231.read_datetime() self.max44009.configure(0, 0, 0, 0) self.display.begin() self.display.clear() self.display.display() outsideTemperature, outsideHumidity, crc_check = self.am2315.sense() for i in range(20): self.rainArray.append(0) def addRainToArray(self, plusRain): del self.rainArray[0] self.rainArray.append(plusRain) def totalRainArray(self): total = 0 for i in range(20): total = total + self.rainArray[i] return total def sampleAndDisplay(self): self.currentWindSpeed = self.weatherStation.current_wind_speed() self.currentWindGust = self.weatherStation.get_wind_gust() self.totalRain = self.totalRain + self.weatherStation.get_current_rain_total( ) logger.debug('Rain Total =\t{0:0.2f} mm'.format( self.totalRain)) logger.debug('Wind Speed =\t{0:0.2f} KMH'.format( self.currentWindSpeed)) logger.debug('KMH wind_gust =\t{0:0.2f} KMH'.format( self.currentWindGust)) logger.debug('Wind Direction =\t{0:0.2f} Degrees'.format( self.weatherStation.current_wind_direction())) logger.debug('Wind Direction Voltage =\t{0:0.3f} V'.format( self.weatherStation.current_wind_direction_voltage())) logger.debug('DS3231 Datetime =\t{0}'.format( self.ds3231.read_datetime())) logger.debug('DS3231 Temperature =\t{0:0.2f} C'.format( self.ds3231.getTemp())) logger.debug('BMP280 Temperature =\t{0:0.2f} C'.format( self.bmp280.read_temperature())) logger.debug('BMP280 Pressure =\t{0:0.2f} KPa'.format( self.bmp280.read_pressure() / 1000)) logger.debug('BMP280 Altitude =\t{0:0.2f} m'.format( self.bmp280.read_altitude())) logger.debug('BMP280 Sealevel Pressure =\t{0:0.2f} KPa'.format( self.bmp280.read_sealevel_pressure() / 1000)) luminosity = self.max44009.luminosity() logger.debug( 'MAX44009 Luminosity =\t{0:0.2f} lux'.format(luminosity)) logger.debug('MAX44009 Solar radiation =\t{0:0.2f} W/m^2'.format( luminosity * 0.0079)) outsideTemperature, outsideHumidity, crc_check = self.am2315.sense() logger.debug('AM2315 outTemperature =\t{0:0.1f} C'.format( outsideTemperature)) logger.debug( 'AM2315 outHumidity =\t{0:0.1f} %'.format(outsideHumidity)) logger.debug('AM2315 crc =\t{0}'.format(crc_check)) logger.debug('dewpoint =\t{0:0.1f} C'.format( self.dew_point(outsideTemperature, outsideHumidity))) logger.debug('heat index =\t{0:0.1f} C'.format( self.heat_index(outsideTemperature, outsideHumidity))) logger.debug('wind chill =\t{0:0.1f} C'.format( self.wind_chill(outsideTemperature, self.currentWindSpeed))) Scroll_SSD1306.addLineOLED(self.display, '{0}'.format(self.ds3231.read_datetime())) Scroll_SSD1306.addLineOLED( self.display, 'IT= {0:0.1f} OT= {1:0.1f} '.format( self.bmp280.read_temperature(), outsideTemperature)) Scroll_SSD1306.addLineOLED( self.display, 'PS= {0:0.1f} HU= {1:0.0f} '.format( (self.bmp280.read_pressure() / 1000), outsideHumidity)) Scroll_SSD1306.addLineOLED( self.display, 'Wind Speed= {0:0.1f} KMH '.format(self.currentWindSpeed)) Scroll_SSD1306.addLineOLED( self.display, 'Wind Dir = {0:0.1f} Deg '.format( self.weatherStation.current_wind_direction())) Scroll_SSD1306.addLineOLED( self.display, 'Rain Total= {0:0.1f} mm '.format(self.totalRain)) def sampleWeather(self): logger.info(" Weather Sampling") # get Weather Sensor data currentWindSpeed = self.weatherStation.current_wind_speed() currentWindGust = self.weatherStation.get_wind_gust() self.totalRain = self.totalRain + self.weatherStation.get_current_rain_total( ) self.currentWindDirection = self.weatherStation.current_wind_direction( ) self.currentWindDirectionVoltage = self.weatherStation.current_wind_direction_voltage( ) # get BMP180 temperature and pressure bmp180Temperature = self.bmp280.read_temperature() bmp180Pressure = self.bmp280.read_pressure() / 1000 bmp180Altitude = self.bmp280.read_altitude() bmp180SeaLevel = self.bmp280.read_sealevel_pressure() / 1000 # get AM2315 Outside Humidity and Outside Temperature outsideTemperature, outsideHumidity, crc_check = self.am2315.sense() # get MAX44009 Luminosity luminosity = self.max44009.luminosity() solarradiation = luminosity * 0.0079 self.addRainToArray(self.totalRain - self.lastRainReading) self.rain60Minutes = self.totalRainArray() self.lastRainReading = self.totalRain logger.info("rain in past 60 minute= %s" % self.rain60Minutes) logger.info("Sending Data to WeatherUnderground") if (WeatherUnderground_Enable): # build the URL myURL = "/weatherstation/updateweatherstation.php?" myURL += "ID=" + WeatherUnderground_StationID myURL += "&PASSWORD="******"&dateutc=now" # now weather station variables myURL += "&winddir=%i" % currentWindDirection myURL += "&windspeedmph=%0.2f" % (currentWindSpeed / 1.6) myURL += "&humidity=%i" % outsideHumidity myURL += "&tempf=%0.2f" % ((outsideTemperature * 9.0 / 5.0) + 32.0) myURL += "&rainin=%0.2f" % ((self.rain60Minutes) / 25.4) myURL += "&baromin=%0.2f" % ((bmp180SeaLevel) * 0.2953) myURL += "&solarradiation=%0.2f" % solarradiation myURL += "&software=GroveWeatherPi" #send it conn = httplib.HTTPConnection("weatherstation.wunderground.com") conn.request("GET", myURL) res = conn.getresponse() logger.debug(res.status + res.reason) textresponse = res.read() logger.debug(textresponse) conn.close() logger.info("Storing Data into DB") if (DB_Enable): session = DBSession() data = WeatherData( datetime=datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S'), windspeed=currentWindSpeed, winddir=self.currentWindDirection, windgust=currentWindGust, barometer=bmp180Pressure, inhumidity=outsideHumidity, outhumidity=outsideHumidity, intemp=bmp180Temperature, outtemp=outsideTemperature, rain=self.lastRainReading, dewpoint=self.dew_point(outsideTemperature, outsideHumidity), heatindex=self.heat_index(outsideTemperature, outsideHumidity), windchill=self.wind_chill(outsideTemperature, self.currentWindSpeed), luminosity=luminosity, radiation=solarradiation) session.add(data) session.commit() def heat_index(self, temperature, humidity): c2f = lambda t: t * 9 / 5. + 32 f2c = lambda t: (t - 32) * 5 / 9. c1 = -42.379 c2 = 2.04901523 c3 = 10.14333127 c4 = -0.22475541 c5 = -6.83783e-3 c6 = -5.481717e-2 c7 = 1.22874e-3 c8 = 8.5282e-4 c9 = -1.99e-6 T = c2f(temperature) # try simplified formula first (used for HI < 80) HI = 0.5 * (T + 61. + (T - 68.) * 1.2 + humidity * 0.094) if HI >= 80: # use Rothfusz regression HI = math.fsum([ c1, c2 * T, c3 * RH, c4 * T * humidity, c5 * T**2, c6 * humidity**2, c7 * T**2 * humidity, c8 * T * humidity**2, c9 * T**2 * humidity**2, ]) return f2c(HI) def dew_point(self, temperature, humidity): CONSTANTS = dict( positive=dict(b=17.368, c=238.88), negative=dict(b=17.966, c=247.15), ) const = CONSTANTS['positive'] if temperature > 0 else CONSTANTS[ 'negative'] pa = humidity / 100. * math.exp(const['b'] * temperature / (const['c'] + temperature)) return const['c'] * math.log(pa) / (const['b'] - math.log(pa)) def wind_chill(self, temp, wind_speed): return 35.74 + (0.6215 * temp) - 35.75 * (wind_speed ** 0.16) \ + 0.4275 * temp * (wind_speed ** 0.16)
GAIN = 1 ADC_WIND_DIRECTION_CHANNEL = 1 adc = Adafruit_ADS1x15.ADS1115(address=0x49) ## wind KMH_PER_TICK_SECOND = 2.4 wind_lock = threading.Semaphore() # rain # MM_PER_TICK = 0.2794 MM_PER_TICK = -0.2794 # disable rain by making it negative rain_lock = threading.Semaphore() # pressure INHG_PER_PA = 0.0002953 bmp = BMP280.BMP280() # humidity am = am2315_i2cfix() # hack to generate fake rain from threading import Timer rain_ticks = 0 def make_rain(): ticks = 1 with rain_lock: global rain_ticks rain_ticks = rain_ticks + ticks t = Timer(10, make_rain)
def main(): time = dt.datetime.now() #Get MCP9808 Temp Data try: mcp1 = MCP9808.MCP9808() mcp1.begin() mcp1_temp = mcp1.readTempC() except: try: mcp1 = MCP9808.MCP9808() mcp1.begin() mcp1_temp = mcp1.readTempC() except: mcp1_temp = -9999. try: mcp2 = MCP9808.MCP9808(address=0x19) #Pi Temp mcp2.begin() mcp2_temp = mcp2.readTempC() except: mcp2_temp = -9999. #Get HTU2D RH/Temp Data try: htu = HTU21D.HTU21D() htu_temp = htu.read_temperature() htu_rh = htu.read_humidity() htu_dp = htu.read_dewpoint() except: htu_temp = -9999. htu_rh = -9999. htu_dp = -9999. #Get BMP pressure and temp data try: bmp = BMP280.BMP280() bmp_temp = bmp.read_temperature() bmp_pressure = bmp.read_pressure() bmp_alt = bmp.read_altitude() bmp_slp = bmp.read_sealevel_pressure() except: bmp_temp = -9999. bmp_pressure = -9999. bmp_alt = -9999. bmp_slp = -9999. #Get UV data try: si = SI1145.SI1145() si_vis = si.readVisible() si_ir = si.readIR() si_uv = si.readUV() si_uv = si_uv / 100.0 except: si_vis = -9999. si_ir = -9999. si_uv = -9999. #Write Data out to files path = '/home/pi/data/cimms' #Check if directories exist, if not create them inst_dirs = ['mcp1', 'mcp2', 'htu', 'bmp', 'si', 'master'] for d in inst_dirs: if not os.path.exists(os.path.join(path, d)): os.makedirs(os.path.join(path, d)) data = [time] #Write Individual Files #MCP9808 Main Sensor fname = os.path.join( path, inst_dirs[0], 'mcp9808_1_%4d%02d%02d.csv' % (time.year, time.month, time.day)) fd = open(fname, 'a+') fd.write(','.join([str(time), str(mcp1_temp)]) + '\n') fd.close() #MCP9808 Logger Sensor fname = os.path.join( path, inst_dirs[1], 'mcp9808_2_%4d%02d%02d.csv' % (time.year, time.month, time.day)) fd = open(fname, 'a+') fd.write(','.join([str(time), str(mcp2_temp)]) + '\n') fd.close() #HTU21D Humidity Sensor fname = os.path.join( path, inst_dirs[2], 'htu21d_%4d%02d%02d.csv' % (time.year, time.month, time.day)) fd = open(fname, 'a+') fd.write(','.join( [str(time), str(htu_temp), str(htu_dp), str(htu_rh)]) + '\n') fd.close() #BMP280 Pressure Sensor fname = os.path.join( path, inst_dirs[3], 'bmp280_%4d%02d%02d.csv' % (time.year, time.month, time.day)) fd = open(fname, 'a+') fd.write(','.join([ str(time), str(bmp_temp), str(bmp_pressure), str(bmp_alt), str(bmp_slp) ]) + '\n') fd.close() #SI1145 UV Sensor fname = os.path.join( path, inst_dirs[4], 'si1145_%4d%02d%02d.csv' % (time.year, time.month, time.day)) fd = open(fname, 'a+') fd.write(','.join([str(time), str(si_vis), str(si_ir), str(si_uv)]) + '\n') fd.close() #Write out all data to master file fname = os.path.join( path, inst_dirs[5], 'cimms_wxst_%4d%02d%02d.csv' % (time.year, time.month, time.day)) fd = open(fname, 'a+') fd.write(','.join([ str(time), str(round(mcp1_temp, 2)), str(round(mcp2_temp, 2)), str(round(htu_temp, 2)), str(round(htu_dp, 2)), str(round(htu_rh, 2)), str(round(bmp_temp, 2)), str(round(bmp_pressure, 2)), str(round(bmp_alt, 2)), str(round(bmp_slp, 2)), str(round(si_vis, 2)), str(round(si_ir, 2)), str(round(si_uv, 2)) ]) + '\n') fd.close()
if equals_pos != -1: temp_string = lines[1][equals_pos + 2:] temp_c = float(temp_string) / 1000.0 return temp_c ###### -Humidity- ######################### # Sensor should be set to Adafruit_DHT.DHT11, # Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302. DHTSensor = Adafruit_DHT.DHT11 # Hier kann der Pin deklariert werden, an dem das Sensormodul angeschlossen ist GPIO_pin_humidity = 23 ###### -Preassure- ######################### preassureSensor = BMP280.BMP280() ###### -Battery- ######################### batteryLife = 100 def currTemp(): return TemperaturAuswertung() def currHumid(): humidity, temp = Adafruit_DHT.read_retry(DHTSensor, GPIO_pin_humidity) return humidity def currPreassure():
#print "----------------- " #print "writing first 4 addresses with random data" for x in range(0, 4): value = random.randint(0, 255) #print "address = %i writing value=%i" % (x, value) ds3231.write_AT24C32_byte(x, value) #print "----------------- " #print "reading first 4 addresses" #for x in range(0,4): #print "address = %i value = %i" %(x, ds3231.read_AT24C32_byte(x)) #print "----------------- " ################ # BMP280 Setup bmp280 = BMP280.BMP280(busnum=1) ################ # OLED SSD_1306 Detection # display = Adafruit_SSD1306.SSD1306_128_64(rst=RST, i2c_address=0x3C) # # Initialize library. # display.begin() # display.clear() # display.display() ################ # ad3935 Set up Lightning Detector # switch to BUS1 - lightning detector is on Bus1
def __init__(self, config): super(GPIOBMP280Input, self).__init__(config) self.address = self.config["address"] self.bmp280 = BMP280.BMP280(address=self.address)
def __init__(self, **stn_dict): self._sensor1 = BMP280.BMP280() self._sensor2 = Adafruit_DHT.AM2302 self._pin = 17
#!/usr/bin/python import Adafruit_BMP.BMP280 as BMP280 import requests import pip._vendor.requests import time import json #data = json.loads(urlopen('http://192.168.2.109/daten.json').read()) #import myopenfile with open('/home/pi/Documents/daten.json') as f: data = json.load(f) #data = {} print(data) sensor = BMP280.BMP280(address=0x76) localtime = time.asctime(time.localtime(time.time())) temperature = sensor.read_temperature() pressure = sensor.read_pressure() #humidity = sensor.read_humidity() print "Temperature : ", temperature, "C" print "Pressure : ", pressure / 100, "hPa" #print "Humidity : ", humidity, "%" f = open("Data.txt", "a") f.write("\n" + str(localtime) + ", temp: " + str(temperature) + ", Druck: " + str(pressure)) f.close() #data['people'] = [] data.append({'time': localtime, 'temp': temperature, 'druck': pressure}) with open('/home/pi/Documents/daten.json', 'w') as outfile: