示例#1
0
def setup_sensors(i2c):

    while True:
        try:
            bme = bme280.BME280(i2c=i2c)
            light_sensor = max44009.MAX44009(i2c)
            break
        except Exception as e:
            print("One sensor couldn't be initialized: {}".format(e))
            time.sleep(3)
            continue

    print("Sensors ready")

    return bme, light_sensor
示例#2
0
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)
#!/usr/bin/env python

import sys
import time

sys.path.append('./')

import max44009

# Main Program

print ""
print "Test Max44009"
print ""

max_sensor = max44009.MAX44009(1, 0x4a)

max_sensor.configure(cont=0, manual=0, cdr=0, timer=0)

# Main Loop - sleeps 2 seconds, then reads and print luminosity values

while True:
    print "Ambient Light luminance : %.2f lux" % max_sensor.luminosity()
    time.sleep(2.0)
示例#4
0
owTemp = []  # Lista com as temperaturas lidas com o OneWire

light_s = False  # Flag para indicar se o MAX44009 esta conectado
bme_s = False  # Flag para indicar se o BME280 esta conectado
ow_s = False  # Flag para indicar se possui algum sensor 1-Wire conectado
if len(connectedOW) > 0:
    ow_s = True

connected_i2c = False  # Flag para indicar se possui algum sensor I2C conectado
if len(connectedI2C) > 0:
    connected_i2c = True

if connected_i2c:
    for device in connectedI2C:
        if device == 0x4A:  # MAX44009 - 74
            light_sensor = max44009.MAX44009(i2c)
            light_s = True
        elif device == 0x76:  # BME280 - 118
            bme = bme280.BME280(i2c=i2c,
                                pressure_mode=bme280.OSAMPLE_8,
                                iir=bme280.FILTER_8)
            bme_s = True
        else:
            if flagDebug:
                print("I2C nao reconhecido")  # Dispositivo nao cadastrado

if ow_s:
    count = 0
    for sensors in connectedOW:
        temp.start_conversion(temp.roms[count])
        count += 1
示例#5
0
# I2C Иницилизация
i2c_bme = I2C(scl=Pin(22), sda=Pin(21), freq=10000)
i2c_oled = I2C(-1, scl=Pin(17), sda=Pin(16))
i2c_lux = I2C(scl=Pin(4), sda=Pin(0))

# Иницилизация экрана
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c_oled)

# Иницилизация датчика BME280
bme_c = bme.BME280(i2c=i2c_bme)

# Иницилизация датчика GY-49
luxometer = max44009.MAX44009(i2c=i2c_lux)

n = 0
while True:

    # Чистка экрана
    oled.fill(0)

    # Получение данных с датчиков
    temp = round(float(bme_c.temperature), 2)
    hum = round(float(bme_c.humidity), 2)
    pres = round(bme_c.pressure * 0.75, 2)
    lux = round(float(luxometer.illuminance_lux), 2)

    # Вывод на экран
    oled.text('Temp: {0}'.format(temp), 0, 10)