Пример #1
0
 def read(self):
     try:
         self.am = AM2315(0x5c, "/dev/i2c-" + self.I2C_bus_number)
         temperature, humidity, crc_check = self.am.sense()
         if crc_check != 1:
             self._temperature = self._humidity = self._crc_check = None
             return 1
         else:
             self._temperature = temperature
             self._humidity = humidity
             self._crc_check = crc_check
     except:
         return 1
Пример #2
0
def test_outdoor_temp():
    logging.info('Testing Outdoor Temperature Sensor (AM2315)...')
    try:
        crc_check = -1
        while crc_check < 0:
            outdoor_temp = AM2315(0x5c, "/dev/i2c-1")
            outside_temperature, outside_humidity, crc_check = outdoor_temp.sense(
            )
            sleep(0.5)
        logging.info("Outside Temperature: %0.1f F",
                     (outside_temperature * 1.8) + 32)
        logging.info("Outside Humidity: %0.1f", outside_humidity)
        logging.info("CRC: %i", crc_check)
        logging.info('Outdoor Temperature Test was Successful (AM2315)')

    except Exception as exc:
        logging.error('Outdoor Temperature Test Failed')
Пример #3
0
    def test_outdoor_temp(self):
        # if self._i2cmux is None:
        #     self.test_i2c_mux()

        # self._i2cmux.write_control_register(TCA9545_CONFIG_BUS0)

        logging.info('Testing Outdoor Temperature Sensor (AM2315)...')
        try:
            crc_check = -1
            while crc_check <> 1:
                self._outdoor_temp = AM2315(0x5c, "/dev/i2c-1")
                outside_temperature, outside_humidity, crc_check = self._outdoor_temp.sense(
                )
                time.sleep(0.5)
            logging.info("Outside Temperature: %0.1f F",
                         (outside_temperature * 1.8) + 32)
            logging.info("Outside Humidity: %0.1f", outside_humidity)
            logging.info("CRC: %i", crc_check)
            logging.info('Outdoor Temperature Test was Successful (AM2315)')

        except Exception as exc:
            logging.error('Outdoor Temperature Test Failed')
Пример #4
0
def main():
    # ONLY DO THIS ONCE.
    #  Calling it in a loop will lead to
    #  a plague of open file handles that will
    #  crash the code silently
    try:
        # I don't know why the hell this doesn't show up in i2cdetect :-/
        am = AM2315(0x5c, "/dev/i2c-1")
    except:
        logger.error("Shit's broken!")
        sys.exit(-1)

    while True:
        now = datetime.datetime.utcnow()
        temp, humi, crc = am.sense()
        lstr = "%s %0.2f %0.2f %s" % (now, temp, humi, (crc == 1))
        # Putting this into the rotating log for now so it's easy to check on
        writeDB([now, temp, humi, (crc == 1)],
                "CourtyardPalmdale.db",
                which="LabEnv")
        logger.info(lstr)
        time.sleep(5)
Пример #5
0
 def __init__(self, i2c_adress=0x5c, i2c_bus="/dev/i2c-1"):
     self.am = AM2315(i2c_adress, i2c_bus)
     self.temperature = 0
     self.humidity = 0
     self.crc_check = 0
Пример #6
0
    as3935Interrupt = True


#as3935pin = 18
as3935pin = 22

GPIO.setup(as3935pin, GPIO.IN)
#GPIO.setup(as3935pin, GPIO.IN,pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(as3935pin, GPIO.RISING, callback=handle_as3935_interrupt)

##############
# Setup AM2315
# turn I2CBus 1 on
tca9545.write_control_register(TCA9545_CONFIG_BUS1)

am2315 = AM2315(0x5c, "/dev/i2c-1")

###############

# Set up FRAM
# turn I2CBus 0 on
tca9545.write_control_register(TCA9545_CONFIG_BUS0)

#fram = SDL_Pi_FRAM.SDL_Pi_FRAM(addr = 0x50)

# Main Loop - sleeps 10 seconds
# command from RasPiConnect Execution Code


def completeCommand():
Пример #7
0
## INIT GPIOs
INIT_GPIOs()

## init 16x2 display
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(LCD_E, GPIO.OUT)
GPIO.setup(LCD_RS, GPIO.OUT)
GPIO.setup(LCD_DATA4, GPIO.OUT)
GPIO.setup(LCD_DATA5, GPIO.OUT)
GPIO.setup(LCD_DATA6, GPIO.OUT)
GPIO.setup(LCD_DATA7, GPIO.OUT)
display_init()

## init sensors and data
sens_A = AM2315(0x5c,"/dev/i2c-1")
sens_K = AM2315(0x5c,"/dev/i2c-3")

while True:
  # read sensor data
  TA, HA, crcA_check = sens_A.sense()
  TK, HK, crcK_check = sens_K.sense()
  TI, HI, validI_check = HYT221(0x28,1)

  # check if data validity
  if crcA_check == 1 and crcK_check == 1 and validI_check == 1:
    if debug == 1:
      #Print result
      print "A= T: %0.1f" % TA,"H: %0.1f" % HA, "crc_ok: %s" % (crcA_check == 1)
      print "I= T: %0.1f" % TI,"H: %0.1f" % HI, "crc_ok: %s" % (validI_check == 1)
      print "K= T: %0.1f" % TK,"H: %0.1f" % HK, "crc_ok: %s" % (crcK_check == 1)
Пример #8
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)
Пример #9
0
 def __init__(self, address, i2c_port="/dev/i2c-1", **kwargs):
     super(WeatherAM2315, self).__init__(**kwargs)
     self.am2315 = AM2315(address, i2c_port)
Пример #10
0
import time
from tentacle_pi.AM2315 import AM2315

am = AM2315(0x5c, "/dev/i2c-3")

for x in range(0, 10):
    temperature, humidity, crc_check = am.sense()
    print "temperature: %0.1f" % temperature
    print "humidity: %0.1f" % humidity
    print "crc: %s" % crc_check
    print
    time.sleep(2.0)
import os
import sys
import time

from tentacle_pi.AM2315 import AM2315

if not os.geteuid() == 0:
    print("Error: Script must be executed as root.\n")
    sys.exit(1)

if GPIO.RPI_REVISION in [2, 3]:
    I2C_device = "/dev/i2c-1"
else:
    I2C_device = "/dev/i2c-0"

am = AM2315(0x5c, I2C_device)

now = time.time()
fault = None
faultreset = True
count = 0

date_format = '%Y-%m-%d %H:%M:%S'

while 1:
    temperature, humidity, crc_check = am.sense()
    print("Temperature: {}, Humidity: {}, CRC: {}".format(
        temperature, humidity, crc_check))

    if count:
        date_now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now))
Пример #12
0
def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    am = AM2315(0x5c, "/dev/i2c-1")
    temperature, humidity, crc_check = am.sense()
    message = str(temperature) + ' ' + str(humidity)
    client.publish("home/pi/sensor/am2315", message)
Пример #13
0
def on_message(client, userdata, msg):
    am = AM2315(0x5c, "/dev/i2c-1")
    temperature, humidity, crc_check = am.sense()
    message = str(temperature) + ' ' + str(humidity)
    client.publish("home/sensor/am2315", message)
Пример #14
0
from tentacle_pi.TSL2561 import TSL2561
from tentacle_pi.MCP9808 import MCP9808
from tentacle_pi.MPL115A2 import MPL115A2
from tentacle_pi.LM75 import LM75
"""
Simple test to check if all supported sensors are working.

- Runs on a Odroid C1 (Ubuntu) and Raspberry Pi 1 / 2 (Raspbian).
- For the Banana Pi (Raspbian) change the variable I2C_DEVICE to '/dev/i2c-2'

"""

I2C_DEVICE = '/dev/i2c-1'

print "test AM2315"
am = AM2315(0x5c, I2C_DEVICE)
temperature, humidity, crc_check = am.sense()
print "temperature: %0.1f" % temperature
print "humidity: %0.1f" % humidity
print "crc: %s" % crc_check
print
time.sleep(2)

print "test BMP180"
bmp = BMP180(0x77, I2C_DEVICE)
print "temperature: %0.1f" % bmp.temperature()
print "pressure: %s" % bmp.pressure()
print "altitude: %0.1f" % bmp.altitude()
print
time.sleep(2)
Пример #15
0
VWC = {}
GAIN = 1
maxT_Cpu = 80
minT_Cpu = 0
okT_Cpu = 45
tank_empty = 0
tank_full = 125

#Rockwool temperature setup (SENSOR DS18B20)
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
base_dir = '/sys/bus/w1/devices/'
device_folders = glob.glob(base_dir + '28*')

# AIR TEMPERATURE AND HUMIDITY 2X AM2315
am_in = AM2315(0x5c, "/dev/i2c-1")  # default I2C bus
am_out = AM2315(
    0x5c,
    "/dev/i2c-3")  # new I2C bus created on pins GPIO23 (SDA) and GPIO24 (SCL)

# END OF GLOBAL VARIABLES
""" LIST THAT WILL STORE TEMPERATURES - DS18B20 """
temperatures = []
""" *** SAYS GOOD BYE WHEN PROGRAM STOPS *** """


def exit_handler():
    print 'LivingSense stopped TRANSMITTING DATA. See you soon!'
    GPIO.cleanup()
    return