Esempio n. 1
0
 def __init__(self):
     self.i2c = I2C(scl=Pin(5), sda=Pin(4), freq=400000)  #i2c settings
     self.display = sh1106.SH1106_I2C(
         128, 64, self.i2c, Pin(16),
         0x3c)  #Load the driver and set it to "display"
     self.bme = BME280.BME280(i2c=self.i2c)  #sensor function
     self.pump = PWM(Pin(14), freq=0,
                     duty=0)  #create PWM objekt and configure pump forward
     #self.pump_reverse = PWM(Pin(12), freq=0, duty=0) #create PWM objekt and configure pump backwards
     #self.button = Pin(0, Pin.IN, Pin.PULL_UP) #initialize button
     self.adc = ads1x15.ADS1115(
         self.i2c, self.addr, self.gain
     )  #create analog-digtial converter object to read analog humidity sensor
     self.time_start = time.ticks_ms() / 1000  #Sekunden
     self.autosetinterval = time.ticks_ms() / 1000 + 25200  #counter
     self.time_current = 0
     self.time_start = 0
     self.reset = 0
     self.epoche = 0
     self.water_storage = 1.2
     self.water_use = 0
     self.water_status = True
     self.button = Pin(0, Pin.IN, Pin.PULL_UP)
     self.button.irq(trigger=Pin.IRQ_FALLING, handler=self.handle_interrupt)
     self.soil_dry = 20000  #CSensor >20000 /Annahme Test offen
     self.soil_ok = 15000  #CSensor 15000 bis 10000 /Annahme Test offen
     self.soil_humid = 10000  #CSensor 250 - bis 10000 /Annahme Test offen
     #self.soil_humidity = None
     self.activateAndClearDisplay()
Esempio n. 2
0
def Sensor_Read(t):
    import ads1x15, bme680
    from machine import Pin,I2C
    #Turn on sensor
    SO = Pin(4,Pin.OUT)
    SO.on()
    i2c = I2C(scl=Pin(22),sda=Pin(21))
    i2c.init(scl=Pin(22),sda=Pin(21))
    i2c.scan()
    #address=0x77
    bme = bme680.BME680_I2C(i2c)
    adc = ads1x15.ADS1115(i2c)
    iaq_read = 0
    iaq_pred = 0
    iaq_stat = 0
    iaq_b3 = 0
    iaq_resist = 0
    iaq_tvoc = 0

    data = []
    for i in range(t):
        time.sleep(1)
        S1 = adc.read(channel1=0) * 0.125
        S2 = adc.read(channel1=1) * 0.125
        S3 = adc.read(channel1=2) * 0.125
        S4 = adc.read(channel1=3) * 0.125
        S5 = bme.temperature#temperature
        S6 = bme.humidity#humidity
        S7 = bme.pressure#pressure
        S8 = bme.gas#gas
        try:
            iaq_read = i2c.readfrom(90,9)
        except:
            print("etimedout")
            i2c = I2C(scl=Pin(22),sda=Pin(21))
            i2c.init(scl=Pin(22),sda=Pin(21))
            i2c.scan()
            iaq_read = i2c.readfrom(90,9)
        #bug: if the first reading is the error?
        if iaq_read[8]==255 and iaq_read[7]==255:
            iaq_pred = iaq_pred
            iaq_stat = iaq_stat
            iaq_b3 = iaq_b3
            iaq_resist = iaq_resist
            iaq_tvoc = iaq_tvoc
        else:
            iaq_pred = (iaq_read[0]*2**8)+iaq_read[1]
            iaq_stat = iaq_read[2]
            iaq_b3 = iaq_read[3]
            iaq_resist = (iaq_read[4]*2**(16))+(iaq_read[5]*2**8)+iaq_read[6]
            iaq_tvoc = (iaq_read[7]*2**8)+iaq_read[8]
        S9 = iaq_pred
        S10 = iaq_resist
        S11 = iaq_tvoc
        S12=random.uniform(100,5000)
        data.append([S1,S2,S3,S4,S5,S6,S7,S8,S9,S10,S11,S12])
    return data
class MyMachine:
    # physical interfaces
    i2c = None
    display = None
    bme = None
    pump = None
    pump_reverse = None
    button = None
    adc = None
    # sensor variables
    temp = None
    hum = None
    pres = None
    volt = None
    water_storage = None
    water_storage_max = 1.2
    time_current = None
    epoche = 0  #Epoche
    # fixed values
    addr = 0x48
    gain = 1
    time_start = time.ticks_ms()  #start Wert des internen Zählers
    #config
    i2c = I2C(scl=Pin(5), sda=Pin(4), freq=400000)  #i2c settings
    display = sh1106.SH1106_I2C(128, 64, i2c, Pin(16),
                                0x3c)  #Load the driver and set it to "display"
    display.sleep(False)  #activate display
    display.fill(0)  #clear display
    bme = BME280.BME280(i2c=i2c)  #sensor function
    pumpe = PWM(Pin(14), freq=0,
                duty=0)  #create PWM objekt and configure pump forward
    pumpe_reverse = PWM(
        Pin(12), freq=0,
        duty=0)  #create PWM objekt and configure pump backwards
    button = Pin(0, Pin.IN, Pin.PULL_UP)  #initialize button
    addr = 0x48
    gain = 1
    adc = ads1x15.ADS1115(
        i2c, addr, gain
    )  #create analog-digtial converter object to read analog humidity sensor
    i = 0
    start = time.ticks_ms()  #start Wert des internen Zaehlers
    autosetinterval = 25200  #counter
    reset = 0  #reset for time counter
Esempio n. 4
0
from machine import I2C, Pin
from time import sleep_ms
import ads1x15

addr = 74
gain = 1

i2c = I2C(scl=Pin(5), sda=Pin(4), freq=400000)
ads = ads1x15.ADS1115(i2c, addr, gain)


def TempC(voltage):
    degC = ((voltage * 1000) - 500) / 10
    return degC


def main():
    while True:
        voltage = ads.raw_to_v(ads.read(channel1=0)) + 0.01
        print('voltage:{}, Temp C:{}'.format(voltage, TempC(voltage)))
        sleep_ms(1000)


try:
    main()
except:
    print('Bye')
Esempio n. 5
0
import machine
from machine import Pin, I2C, ADC
import time
import urequests
from time import sleep
import ads1x15

i2c = machine.I2C(-1, scl=machine.Pin(32), sda=machine.Pin(27))
ag_address = 72  #analog address
gain = 0  #analog read gain (0-6.144v)
adc_1115 = ads1x15.ADS1115(i2c, ag_address, gain)  #voltage analog
raw_v = adc_1115.read(1, 0)
volt = adc_1115.raw_to_v(raw_v)  #converted voltage
print(volt)
Esempio n. 6
0

led = ledCtrl()
#set LED purple while device configuring
led.purple()
buzz = buzzCtrl()
"""
Set up I2C
"""
i2c = machine.I2C(scl=machine.Pin(5), sda=machine.Pin(4), freq=100000)
print('Devices attached:')
print(i2c.scan())

#Set up ADC
print('Setting up ADC')
adc = ads1x15.ADS1115(i2c)
adc.gain = 1
#ADS1015_REG_CONFIG_PGA_4_096V

#Set up LIS3DH
print('Setting up LIS3DH')
setUpAccel()
"""
Set up Network
"""
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.scan()  # Scan for available access points
sta_if.connect(wifi_ssid, wifi_passw)  # Connect to an AP
# Check for successful connection
connectCount = 0
Esempio n. 7
0
class sensors:
    with open("config.py") as json_data_file:
        conf = ujson.load(json_data_file)

    import utime
    led = Pin(2, Pin.OUT)  #internal LED is on pin 2

    i2c = I2C(scl=Pin(22), sda=Pin(21), freq=10000)
    print('Scanning i2c bus...')
    devices = i2c.scan()
    if len(devices) == 0:
        print("No i2c device !")
    else:
        print('i2c devices found:', len(devices))
        for device in devices:
            print("Decimal address: ", device, " | Hexa address: ",
                  hex(device))

    onewirePin = machine.Pin(15)
    wire = onewire.OneWire(onewirePin)
    try:
        ds = ds18x20.DS18X20(wire)
        roms = ds.scan()
        # roms.append(roms[0])
        if roms == []:
            roms = 0
        for rom in roms:
            print('      DS18b20  devices:', int.from_bytes(rom, 'little'),
                  hex(int.from_bytes(rom, 'little')))
    except Exception as e:
        conf['Run_DS18B20'] = 'false'
        print("      DS18B20 start error - ", e)

#////////////////// INA setup /////////////////////////
    try:
        SHUNT_OHMS = 0.1
        ina = INA219(SHUNT_OHMS, i2c)
        print('INA219 instance created')
    except Exception as e:
        print("      INA start error - ", e)

    try:
        ina.configure()  # gain defaults to 3.2A. ina219.py line 132
        print('     INA219 instance configure run')
    except Exception as e:
        print('INA configure failed, possibly not connected. Error=', e)

#////////////////// BME setup /////////////////////////
    try:
        bme = bme280_float.BME280(i2c=i2c)
        print('BME started')
    except Exception as e:
        print('BME start failed, possibly not connected. Error=', e)

#////////////////// ADS1115 setup /////////////////////
#ads1115 set up, , 0x48 default, 0x4a->connect ADDR pin to SDA
    try:
        addr = 0x4a
        gain = 0
        ads1115A = ads1x15.ADS1115(i2c, addr, gain)
        print("ADS1115A started")
    except Exception as e:
        print('ADS1115A start failed, possibly not connected. Error=', e)

    try:
        addr = 0x48
        gain = 0
        ads1115B = ads1x15.ADS1115(i2c, addr, gain)
        print("ADS1115B started")

    except Exception as e:
        print('ADS1115B start failed, possibly not connected. Error=', e)
#___________________________________________________________________________________________
#////////////////// INIT /// /////////////////////////

    def __init__(self):
        for key in self.conf.keys():
            print(key, "---", self.conf[key])

        print('new sensors instance created')

    def debugPrint1(self, message):
        if self.conf['debugPrint1'] == 'True':
            print(message)

    def connectWifi(self):
        import network
        sta_if = network.WLAN(network.STA_IF)
        print('\n', 'sta_if.active = ', sta_if.active(), '\n')
        sta_if.active(True)
        print('\n', 'sta_if.active = ', sta_if.active(), '\n')
        networks = sta_if.scan()

        if not sta_if.isconnected():
            print('        connecting to network...')

            print('\n', '        No. of networks = ', len(networks), '\n')
            print('        networks = ', networks, '\n')
            try:
                sta_if.ifconfig((self.conf['IP_Address'], '255.255.255.0',
                                 '10.10.10.1', '10.10.10.1'))
                sta_if.connect(self.conf['ssid'], self.conf['password'])
                self.udpAddr = '10.10.10.1'
            except Exception as e:
                print('connect wifi failure, error =', e)
                pass

            counter = 0
            while not sta_if.isconnected():
                utime.sleep(0.25)
                print("\r>", counter, end='')
                counter += 1
                self.flashLed()
                if counter > 100:
                    machine.reset()
                pass
        print('\n', '    CONNECTED!! network config:', sta_if.isconnected(),
              '\n', sta_if.ifconfig(), '\n')

    def flashLed(self):
        self.led.value(not self.led.value())

    def getVoltage(self):
        value = [0, 1, 2, 3]
        voltage = [0, 1, 2, 3]
        calibration = 1
        for i in range(4):  # 0 - 3
            #           def read(self, rate=4, channel1=0, channel2=None):, line 156 ads1x15.py
            try:
                value[i] = self.ads1115A.read(4, i)
                voltage[i] = self.ads1115A.raw_to_v(value[i])
                if i == 2:
                    calibration = 6.09
                elif i == 3:
                    calibration = 6.11
                self.insertIntoSigKdata("electrical.ads1115-1." + str(i),
                                        voltage[i] * calibration)
                calibration = 1
            except Exception as e:
                pass

        try:
            calibration = 6.09
            value = self.ads1115B.read(4, 0, 1)
            voltage = self.ads1115B.raw_to_v(value)
            self.insertIntoSigKdata("electrical.ads1115-2.1",
                                    voltage * calibration)
            calibration = 6.09
            value = self.ads1115B.read(4, 2, 3)
            voltage = self.ads1115B.raw_to_v(value)
            self.insertIntoSigKdata("electrical.ads1115-2.2",
                                    voltage * calibration)
        except Exception as e:
            pass

    def getPressure(self, destination):

        try:
            vals = self.bme.read_compensated_data()
        except Exception as e:
            print('BME failed, possibly not connected. Error=', e)
            pass
        else:
            temp = vals[0]
            pres = vals[1]
            hum = vals[2]
            if destination == 'signalk':
                self.insertIntoSigKdata("environment.outside.humidity",
                                        hum)  # insertIntoSigKdata(path, value)
                self.utime.sleep_ms(100)
                self.insertIntoSigKdata("environment.outside.temperature",
                                        temp + 273.15)
                self.utime.sleep_ms(100)
                self.insertIntoSigKdata("environment.outside.pressure", pres)
                self.utime.sleep_ms(100)
            elif destination == 'influxdb':
                print(' would send to udp here')

    def getCurrent(self):
        try:
            self.insertIntoSigKdata("esp.currentSensor.voltage",
                                    self.ina.voltage())
            self.utime.sleep_ms(100)
            self.insertIntoSigKdata("esp.currentSensor.current",
                                    self.ina.current())
            self.utime.sleep_ms(100)
            self.insertIntoSigKdata("esp.currentSensor.power",
                                    self.ina.power())

        except Exception as e:
            print('INA1 read failed, Error=', e)
            pass

    def getTemp(self):
        try:
            self.ds.convert_temp()
            utime.sleep_ms(200)
            for rom in (self.roms):
                value = self.ds.read_temp(rom)
                if rom == (b'(\x7f@V\x05\x00\x00\xaf'):
                    path = "esp.propulsion.alternator.temperature"
                    self.insertIntoSigKdata(path, value + 273.15)
                elif rom == (b"('\xd4V\x05\x00\x00\x88"):
                    path = "esp.propulsion.exhaust.temperature"
                    self.insertIntoSigKdata(path, value + 273.15)
                elif rom == (b'(a\xdeV\x05\x00\x00\xf2'):
                    path = "esp.propulsion.head.temperature"
                    self.insertIntoSigKdata(path, value + 273.15)
                elif rom == (b'(\xdd\xdfU\x05\x00\x00\xcd'):
                    path = "esp.electrical.batteries.housebank.temperature"
                    self.insertIntoSigKdata(path, value + 273.15)

        except Exception as e:
            print("DS18B20 error Error=", e)
            pass

    def insertIntoSigKdata(self, path, value):
        _sigKdata = {"updates": [{"values": []}]}
        _sigKdata["updates"][0]["values"].append({
            "path": path,
            "value": value
        })
        self.sendToUDP(ujson.dumps(_sigKdata), '10.10.10.1',
                       self.conf['sigK_udp-port'])
        try:
            self.debugPrint1(_sigKdata)
        except Exception as e:
            print("debug print error=", e)

    def sendToUDP(self, message, udpAddr, udpPort):
        try:
            s = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM)
            s.sendto(message, (udpAddr, int(udpPort)))
            s.close()
        except Exception as e:
            print("UDP sending error=", e)
            pass

    def str_to_bool(self, s):
        return str(s).lower() in ("yes", "true", "t", "1")

    def checkConnection(self):
        wlan = network.WLAN(network.STA_IF)
        if not wlan.isconnected():
            print('Not connected to wifi, rebooting...')
            machine.reset()

    def reboot(self):
        print("..rebooting..")
        machine.reset()

    def dataBasesend(self):  #which sensors to send, triggered by timer
        self.flashLed()

    def datasend(self):  #which sensors to send, triggered by timer
        self.flashLed()
        self.insertIntoSigKdata("esp.heartbeat.led", self.led.value())
        if self.conf['Run_BME280'] == 'True':
            self.getPressure('signalk')
        if self.conf['Run_ADS1115'] == 'True':
            self.getVoltage()
        if self.conf['Run_INA-219'] == 'True':
            self.getCurrent()
        if self.conf['Run_DS18B20'] == 'True':
            self.getTemp()
        self.checkConnection()

    def sendi2c(self):
        devices = self.i2c.scan()
        if len(devices) == 0:
            print("No i2c device !")
        else:
            print('i2c devices found:', len(devices))
            for device in devices:
                print("Decimal address: ", device, " | Hexa address: ",
                      hex(device))
Esempio n. 8
0
# GNU General Public License <https://www.gnu.org/licenses>
# STIA436 Course - Spring 2019
# Professor Colin McCormick & Father Chris Wagner
# Copyright (c) 2019 F. Pascal Girard
#
# ADS1x15 code from https://github.com/adafruit/micropython-adafruit-ads1015
# Keep in mind that this I2C board can have up to 4 addresses using the address pin.
# Default is 0x48.
#

import ads1x15
from machine import I2C, Pin       # create an I2C bus object for all I2C-based sensors.

i2c = I2C(scl=Pin(5), sda=Pin(4))  # create the I2C bus
# 16 bit
raw = ads1x15.ADS1115(i2c, address=0x48)


def measure():
    return {
        "A0": raw.read(0),
        "A1": raw.read(1),
        "A2": raw.read(2),
        "A3": raw.read(3)
    }
Esempio n. 9
0
#Define MQTT topics:
TEMPERATURE_CHIPA = "/sensor/Chipa/temperature"
HUMIDITY_CHIPA = "/sensor/Chipa/humidity"
CARBON_MONOXIDE_CHIPA = "/sensor/Chipa/CO"
GAS_ALL_CHIPA = "/sensor/Chipa/All_Gas"
SENSOR_PREFIX = "SENSOR:"
EOL = "\n"

#ADC channels
MQ7_CHANNEL = 0
MQ135_CHANNEL = 1

#Init I2C multi-channel ADC to poll gas sensors
i2c = I2C(scl=Pin(5), sda=Pin(4), freq=400000)
addr = 72
ads = ads1x15.ADS1115(i2c, addr)


def toggleGPIO(p):
    p.value(not p.value())


def GPIO_On(p):
    p.value(1)


def GPIO_Off(p):
    p.value(0)


def getHumidityTemp():