def soil_reading():
    #read moisture level through capacitive touch pad
    ss = Seesaw(i2c_bus, addr=0x36)
    touch = ss.moisture_read()
    time.sleep(1)
    touch2 = ss.moisture_read()
    difference = touch - touch2

    #check sensor for daily errors
    if (difference > 3 or difference < -3):
        print("moisture warning", difference)

    

    #read temperature from  the temperature from the temperature sensor
    temp = ss.get_temp()
    time.sleep(1)
    temp2 = ss.get_temp()
    temp_difference = temp - temp2

    #check sensor for daily errors
    if (temp_difference > 3 or temp_difference < -3):
        print("tempurature warning", temp_difference)
    
    print("temp: ",temp, " moisture: ",touch)
    time.sleep(1)
Beispiel #2
0
class SoilSensor:
    # initialize needed values for communication
    def __init__(self):
        self.i2c_bus = busio.I2C(SCL, SDA)
        # Need to put the address into the sensor constructor for each
        self.ss = Seesaw(self.i2c_bus, addr=0x36)

    # get the soil moisture from the sensor
    def get_moisture(self):
        #i2c_bus = busio.I2C(SCL, SDA)
        # Need to put the address into the sensor constructor for each
        #ss = Seesaw(i2c_bus, addr=0x36)
        # read moisture level through capacitive touch pad
        moisture = self.ss.moisture_read()
        print("Soil Moisture Reading:", moisture)
        return moisture

    # get the soil temperature from the sensor
    def get_temperature(self):
        #i2c_bus = busio.I2C(SCL, SDA)
        # Need to put the address into the sensor constructor for each
        #ss = Seesaw(i2c_bus, addr=0x36)
        # read temperature from the temperature sensor
        temp = self.ss.get_temp()
        print("Soil Temperatured Reading:", temp)
        return temp
Beispiel #3
0
class InputModule(AbstractInput):
    """ A sensor support class that measures soil moisture using adafruit's i2c soil sensor """
    def __init__(self, input_dev, testing=False):
        super(InputModule, self).__init__(input_dev, testing=testing, name=__name__)

        self.sensor = None

        if not testing:
            self.initialize_input()

    def initialize_input(self):
        from adafruit_seesaw.seesaw import Seesaw
        from adafruit_extended_bus import ExtendedI2C

        try:
            self.sensor = Seesaw(
                ExtendedI2C(self.input_dev.i2c_bus),
                addr=int(str(self.input_dev.i2c_location), 16))
        except:
            self.logger.exception("Setting up sensor")

    def get_measurement(self):
        if not self.sensor:
            self.logger.error("Input not set up")
            return

        self.return_dict = copy.deepcopy(measurements_dict)

        if self.is_enabled(0):
            self.value_set(0, self.sensor.moisture_read())

        if self.is_enabled(1):
            self.value_set(1, self.sensor.get_temp())

        return self.return_dict
 def get_temperature(self):
     i2c_bus = busio.I2C(SCL, SDA)
     # Need to put the address into the sensor constructor for each
     ss = Seesaw(i2c_bus, addr=0x36)
     # read temperature from the temperature sensor
     temp = ss.get_temp()
     print("Soil Temperatured Reading:", temp)
     return temp
def get_temp():
    try:
        i2c_bus = busio.I2C(SCL, SDA)
        ss = Seesaw(i2c_bus, addr=0x36)
        # read temperature from the temperature sensor
        temp = ss.get_temp()
        print("Temperature: {0}".format(temp))
        return round(temp, 2)
    except Exception as e:
        return 0
def get_soil():
    try:
        i2c_bus = busio.I2C(SCL, SDA)
        ss = Seesaw(i2c_bus, addr=0x36)
        # read moisture level through capacitive touch pad
        touch = ss.moisture_read()
        # read temperature from the temperature sensor
        temp = ss.get_temp()
        print("Soil moisture: {0}".format(touch))
        return touch
    except Exception as e:
        return 0
Beispiel #7
0
class SeesawSoilSensor(drivers.Sensor):

    i2c_address = 54  # 0x36
    moisture_metric = 'soil-moisture'
    t9e_metric = 'soil-temp'

    def setup(self):
        i2c_bus = busio.I2C(SCL, SDA)
        self.ss = Seesaw(i2c_bus, addr=int(self.i2c_address))

    def read(self):
        # read moisture level through capacitive touch pad
        moisture = self.ss.moisture_read()
        metrics.create_metric_log(self.moisture_metric, moisture)

        # read temperature from the temperature sensor
        t9e = self.ss.get_temp()
        metrics.create_metric_log(self.t9e_metric, t9e)
Beispiel #8
0
class InputModule(AbstractInput):
    """A sensor support class that measures soil moisture using adafruit's i2c soil sensor."""
    def __init__(self, input_dev, testing=False):
        super().__init__(input_dev, testing=testing, name=__name__)

        self.sensor = None

        if not testing:
            self.try_initialize()

    def initialize(self):
        from adafruit_seesaw.seesaw import Seesaw
        from adafruit_extended_bus import ExtendedI2C

        try:
            self.sensor = Seesaw(ExtendedI2C(self.input_dev.i2c_bus),
                                 addr=int(str(self.input_dev.i2c_location),
                                          16))
        except:
            self.logger.exception("Setting up sensor")

    def get_measurement(self):
        if not self.sensor:
            self.logger.error(
                "Error 101: Device not set up. See https://kizniche.github.io/Mycodo/Error-Codes#error-101 for more info."
            )
            return

        self.return_dict = copy.deepcopy(measurements_dict)

        if self.is_enabled(0):
            self.value_set(0, self.sensor.moisture_read())

        if self.is_enabled(1):
            self.value_set(1, self.sensor.get_temp())

        return self.return_dict
Beispiel #9
0
import board
from adafruit_seesaw.seesaw import Seesaw
from busio import I2C

# Create library object using our Bus I2C port
i2c = I2C(board.SCL, board.SDA)
bme680 = adafruit_bme680.Adafruit_BME680_I2C(i2c, address=0x76, debug=False)
ss1 = Seesaw(i2c, addr=0x36)
ss2 = Seesaw(i2c, addr=0x37)
ss3 = Seesaw(i2c, addr=0x38)

# change this to match the location's pressure (hPa) at sea level
bme680.sea_level_pressure = 1014

while True:
    print("\nTemperature: %0.1f C" % bme680.temperature)
    print("Gas: %d ohm" % bme680.gas)
    print("Humidity: %0.1f %%" % bme680.humidity)
    print("Pressure: %0.3f hPa" % bme680.pressure)
    print("Altitude = %0.2f meters" % bme680.altitude)
    touch = ss1.moisture_read()
    temp = ss1.get_temp()
    print("1:   temp: " + str(temp) + "  moisture: " + str(touch))
    touch = ss2.moisture_read()
    temp = ss2.get_temp()
    print("2:   temp: " + str(temp) + "  moisture: " + str(touch))
    touch = ss3.moisture_read()
    temp = ss3.get_temp()
    print("3:   temp: " + str(temp) + "  moisture: " + str(touch))
    time.sleep(1)
Beispiel #10
0
from adafruit_seesaw.seesaw import Seesaw

if __name__ == "__main__":

    i2c_bus = busio.I2C(SCL, SDA)

    ss = Seesaw(i2c_bus, addr=0x36)
    print("Room: Bedroom")
    print("Plant: Pilea Baby Tears\n")

    while True:
        # read moisture level through capacitive touch pad
        touch = ss.moisture_read()

        #read temperature from temperature sensor
        celcius_temp = ss.get_temp()
        fahrenheit_temp = (celcius_temp * (9 / 5)) + 32

        if (touch < 600):
            print("Needs More Water")
            print("Current Temp (F): " + str(fahrenheit_temp) + " Moisture: " +
                  str(touch))
        elif (touch > 1500):
            print("Too Much Water")
            print("Current Temp (F): " + str(fahrenheit_temp) + " Moisture: " +
                  str(touch))

        else:
            print("Temp (F): " + str(fahrenheit_temp) + " Moisture: " +
                  str(touch))
        time.sleep(1)
io.on_subscribe = subscribe
io.on_message = message

# Connect to Adafruit IO
print("Connecting to Adafruit IO...")
io.connect()
plant_feed = "plant"

START = 0

while True:
    # read moisture level through capacitive touch pad
    touch = seesaw.moisture_read()

    # read temperature from the temperature sensor
    temp = seesaw.get_temp()

    if touch < MIN:
        if not LOW:
            io.publish(plant_feed, touch)
            print("published")
        LOW = True

    elif touch >= MIN and time.time() - START > 10:
        io.publish(plant_feed, touch)
        print("published to Adafruit IO")
        START = time.time()
        LOW = False

    print("temp: " + str(temp) + "  moisture: " + str(touch))
    time.sleep(1)
Beispiel #12
0
min_moisture = 2000

for i in range(15):
    moisture_measurement = ss.moisture_read()
    measurements = measurements + moisture_measurement

    if moisture_measurement > max_moisture:
        max_moisture = moisture_measurement

    if moisture_measurement < min_moisture:
        min_moisture = moisture_measurement

avg_moisture = round((measurements / 15))

# read temperature from the temperature sensor
temp = round(ss.get_temp(), 1)

# Operate pump
#if avg_moisture < 1200:
#	waterPlant()

# If a datatype json has been provided, print data as json string
if datatype == 'json':
    epoch_time = int(time.time())
    humidity = '{0:0.1f}%'.format(air_humidity)
    data = '{"Temp": [' + str(epoch_time) + ', ' + str(
        temp) + '], "Humidity": [' + str(
            epoch_time) + ', ' + humidity + '], "Moisture": [' + str(
                epoch_time) + ', ' + str(avg_moisture) + '] }'
    print(data)
else:
Beispiel #13
0
class GardenShelf():

    def __init__(self, config, i2c):
        self._name = config.get('Name', '')
        self._dht = adafruit_dht.DHT22(int(config.get('DhtPin', 0)))
        self._light_pin = int(config.get('LightPin', 0))
        self._water_pin = int(config.get('WaterPin', 0))
        if config.getboolean('UseSS'):
            self._useSS = True
            self._soil_sensor = Seesaw(i2c, addr=int(config.get('SSAddr', 0x0), 16))
            self._soil_min = int(config.get('SSMin', 0))
            self._soil_max = int(config.get('SSMax', 0))
        else:
            self._useSS = False
        self._light_on = False
        self._water_on = False
        self._turn_light_on = int(config.get('LightOn', 0))
        self._turn_light_off = int(config.get('LightOff', 0))
        self._water_on_pct = int(config.get('MoistureOnPct',25))
        self._water_off_pct = int(config.get('MoistureOffPct', 75))
        self._water_on_time = datetime.strptime(config.get('WaterOnTime', '00:00'), '%H:%M').time()
        self._water_off_time = datetime.strptime(config.get('WaterOffTime', '00:00'), '%H:%M').time()
        self._prefix = config.get('Prefix', '')

        GPIO.setup(self._light_pin, GPIO.OUT, initial=GPIO.HIGH)
        GPIO.setup(self._water_pin, GPIO.OUT, initial=GPIO.HIGH)

        self.temperature = 0.0
        self.humidity = 0.0
        self.soil_temp = 0.0
        self.moisture = 0
        self.prev_temperature = 0.0
        self.prev_humidity = 0.0
        self.prev_moisture = 0.0
        self.prev_soil_temp = 0
        self.water = 0
        self.light = 0


    def _set_grow_light(self, status):
        """
        flips the light status
        """
        # control the device (always set, regardless of logging or not)
        if (status):
            GPIO.output(self._light_pin, GPIO.LOW) 
        else:
            GPIO.output(self._light_pin, GPIO.HIGH) 

        # log the info but guard with flag so we don't go overboard
        if (status and not self._light_on):
            logging.info("Turning grow light on")
            self._light_on = True
        elif (not status and self._light_on):
            logging.info("Turning grow light off")
            self._light_on = False


    def _set_water_pump(self, status):
        """
        flips the water pump
        """
        # control the device (always set, regardless of logging or not)
        if (status):
            GPIO.output(self._water_pin, GPIO.LOW) 
        else:
            GPIO.output(self._water_pin, GPIO.HIGH) 

        # log the info but guard with flag so we don't go overboard
        if (status and not self._water_on):
            logging.info("Turning water pump on")
            self._water_on = True
        elif (not status and self._water_on):
            logging.info("Turning water pump off")
            self._water_on = False


    def scale_moisture(self, current):
        return utils.scale_to_percent(current, self._soil_min, self._soil_max)


    def major_loop(self, now):
        # TODO: read the water flow sensor
        # TODO: should probably indicate if there was a sensor read error

        try:
            self.temperature = self._dht.temperature
            self.humidity = self._dht.humidity
        except:
            logging.error("Unable to read temp/humidity sensor")
            self.temperature = self.prev_temperature
            self.humidity = self.prev_humidity

        try:
            if self._useSS:
                self.moisture = self._soil_sensor.moisture_read()
                self.soil_temp = self._soil_sensor.get_temp()
            else:
                self.moisture = 0
                self.soil_temp = 0
        except:
            logging.error("Unable to read soil moisture sensor")
            self.mosisture = self.prev_moisture
            self.soil_temp = self.prev_soil_temp

        # control the grow light
        if (now.hour >= self._turn_light_on) and (now.hour < self._turn_light_off):
            self._set_grow_light(True)
            self.light = 1
        else:
            self._set_grow_light(False)
            self.light = 0

        # control the water pump
        # NOTE: We would like to maybe do this based on the moisture reading, but that
        # seems to be a bit inconsistent. For now, we will use a simple daily timer
        if (now.time() >= self._water_on_time) and (now.time() < self._water_off_time):
            self._set_water_pump(True)
            self.water = 1
        else:
            self._set_water_pump(False)
            self.water = 0

        # if self._scale_moisture(self.mosisture) < self._water_on_pct:
        #     self._set_water_pump(True)
        #     self.water = 1
        # elif self._scale_moisture(touch) > self._water_off_pct:
        #     self._set_water_pump(False)
        #     self.water = 0
        # else:
        #     self.water = 1 if self._water_on else 0

        # store values for next loop
        self.prev_temperature = self.temperature
        self.prev_humidity = self.humidity
        self.prev_moisture = self.moisture
        self.prev_soil_temp = self.soil_temp


    def get_state(self):
        """
        returns the current state of the shelf (and sensors)
        based on the last main loop
        """
        state = {
            self._prefix + 'temp': self.temperature,
            self._prefix + 'humidity': self.humidity,
            self._prefix + 'soiltemp': self.soil_temp,
            self._prefix + 'moisture': self.moisture,
            self._prefix + 'water': self.water,
            self._prefix + 'light': self.light
        }

        return state
Beispiel #14
0
#!/usr/bin/env python3

from board import SCL, SDA
import busio

from adafruit_seesaw.seesaw import Seesaw

i2c_bus = busio.I2C(SCL, SDA)

ss = Seesaw(i2c_bus, addr=0x36)
print(ss.moisture_read())
print(ss.get_temp())
Beispiel #15
0
import time, requests
from board import SCL, SDA
import busio
from adafruit_seesaw.seesaw import Seesaw 
ss = Seesaw(busio.I2C(SCL, SDA), addr=0x36)

heroku = "" #Enter your heroku app URL here
while True:
    requests.post(heroku, data={"temp": ss.get_temp(), "moisture": ss.moisture_read()})
    time.sleep(1)
Beispiel #16
0
    subscribe_result = subscribe_future.result()
    print('Subscribed with {}'.format(str(subscribe_result['qos'])))

    refresh_interval = 10
    time_fetch_interval = 12 * 60  # Approx. minutes to refetch sunrise/sunset

    while True:
        # Initialize Astral time
        city = LocationInfo(args.city, args.region, args.timezone, args.lat,
                            args.long)
        s = sun(observer=city.observer, tzinfo=args.timezone)
        sunrise = s['sunrise']
        sunset = s['sunset']
        tz = sunrise.tzinfo
        for i in range(time_fetch_interval):
            temperature = soil.get_temp()
            capacitance = soil.moisture_read()
            print('Temp: ' + str(temperature) + ' Capacitance: ' +
                  str(capacitance))

            print('Publishing to topic garden/sensorData...')
            mqtt_connection.publish(topic='garden/sensorData',
                                    payload=json.dumps({
                                        'temperature':
                                        temperature,
                                        'capacitance':
                                        capacitance
                                    }),
                                    qos=mqtt.QoS.AT_LEAST_ONCE)

            if sunrise < datetime.now(tz=tz) < sunset:
Beispiel #17
0
signal.signal(signal.SIGINT, signal_handler)


def cf(ctemp):
    if f: return int((ctemp * 9 / 5) + 32)
    else: return float("{:.1f}".format(ctemp))


def pformat(raw):
    if p: return int(((raw - mmin) * 100) / (mmax - mmin))
    else: return float("{:.2f}".format((raw - mmin) / (mmax - mmin)))


print("Loading averages!")
for i in range(n):
    atemp.append(ss.get_temp())
    awet.append(ss.moisture_read())
    time.sleep(.1)

while True:
    now = dt.utcnow()

    atemp.append(ss.get_temp())
    tmean = s.mean(atemp)
    tsd = s.stdev(atemp, xbar=tmean)
    #print(tsd,' | ',cf(tmean),' | ',atemp)
    atemp.pop(0)
    btemp.append(cf(tmean))
    if len(btemp) > 3: btemp.pop(0)
    #print(btemp)
    if len(btemp) > 1 and len(btemp) == len(set(btemp)): temp = btemp[1]
Beispiel #18
0
import time

from board import SCL, SDA
import busio

from adafruit_seesaw.seesaw import Seesaw

i2c_bus = busio.I2C(SCL, SDA)

ss = Seesaw(i2c_bus, addr=0x36)

while True:
    # read moisture level through capacitive touch pad
    touch = ss.moisture_read()

    # read temperature from the temperature sensor
    temp = ss.get_temp()

    print("temp: " + str(temp) + "  moisture: " + str(touch))
    time.sleep(1)
Beispiel #19
0
print('Attempting to connect to %s' % client.broker)
aws_iot.connect()

# Time in seconds since power on
initial = time.monotonic()

while True:
    try:
        gfx.show_aws_status('Listening for msgs...')
        now = time.monotonic()
        if now - initial > (SENSOR_DELAY * 60):
            # read moisture level
            moisture = ss.moisture_read()
            print("Moisture Level: ", moisture)
            # read temperature
            temperature = ss.get_temp()
            # Display Soil Sensor values on pyportal
            temperature = gfx.show_temp(temperature)
            gfx.show_water_level(moisture)
            print('Sending data to AWS IoT...')
            gfx.show_aws_status('Publishing data...')
            # Create a json-formatted device payload
            payload = {
                "state": {
                    "reported": {
                        "moisture": str(moisture),
                        "temp": str(temperature)
                    }
                }
            }
            # Update device shadow
Beispiel #20
0
LIGHT_TIME_HIGH = 8
LUX_HIGH = 20000
LUX_LOW = 400

temp_list = []
moist_list = []
lux_list = []
light_time = 0
night_time = 0
while True:

    print("received data in ", int(time.time() - initTime), "seconds")
    initTime = time.time()
    moisture = ss.moisture_read(
    )  # read moisture level through capacitive touch pad
    temp = ss.get_temp()  # read temperature from the temperature sensor
    humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
    lux = lightsensor.lux

    moisture = (100 * moisture / 1023)

    print("temp = ", temp)
    print("humidity = ", humidity)
    print("light = ", lux)
    print("moisture = ", moisture)

    temp_list.append(temp)
    moist_list.append(moisture)
    lux_list.append(lux)

    if (len(temp_list) > 30):
Beispiel #21
0
#This is the tutorial testing for the soil sensor
#Just wired all my sensors and tested them individually
#Tomorrow I wire them all on the same board if I can and run it on a cron command
# to start dumping data into a database with SQLite-
#I will have photos posted on how I wired each sensor up to the bread board
import time

from board import SCL, SDA
import busio
from adafruit_seesaw.seesaw import Seesaw

i2c_bus =busio.I2C(SCL, SDA)
ss = Seesaw(i2c_bus, addr=0x36)

while True:

    #read moisture level through capacitive touch pad
    
    touch = ss.moisture_read()

    #read temperature from  the temperature from the temperature sensor
    temp = ss.get_temp()

    print("temp: " + str(temp) + " moisture: " + str(touch))
    time.sleep(1)

def NeoPixelPattern():
    pixel.fill(BLUE)
    time.sleep(SHORTBLINK)
    pixel.fill(NAVY)
    time.sleep(LONGBLINK)
    pixel.fill(BLUE)
    time.sleep(SHORTBLINK)


while True:
    # When not connected via BLERadio
    ble.start_advertising(advertisement)
    while not ble.connected:
        Stemp = ss.get_temp(
        )  # read soil temperature from the temperature sensor
        Smoist = ss.moisture_read(
        )  # read soil moisture level through capacitive touch pad

        # share data via serial
        print(("temp: " + str(Stemp) + "  moisture: " + str(Smoist)))
        time.sleep(1)
    ble.stop_advertising()

    # When connected via BLERadio
    while ble.connected:
        Stemp = ss.get_temp(
        )  # read soil temperature from the temperature sensor
        Smoist = ss.moisture_read(
        )  # read soil moisture level through capacitive touch pad