def __init__(self):
     printflush("Init")
     self.unhandled_event = False
     printflush('Init LEDs')
     self.leds = {
         'red': Pin(D2, Pin.OUT, value=False),
         'blue': Pin(D3, Pin.OUT, value=False),
         'green': Pin(D4, Pin.OUT, value=False)
     }
     printflush('Init OneWire')
     self.ds_pin = Pin(D1)
     self.ow_inst = OneWire(self.ds_pin)
     self.ds_sensor = DS18X20(self.ow_inst)
     self.temp_id = self.ds_sensor.scan()[0]
     printflush('Temperature sensor: %s' % self.temp_id)
     printflush('set LED red')
     self.leds['red'].on()
     printflush('Instantiate WLAN')
     self.wlan = network.WLAN(network.STA_IF)
     printflush('connect_wlan()')
     self.connect_wlan()
     printflush('turn off red LED')
     self.leds['red'].off()
     printflush('hexlify mac')
     self.mac = hexlify(self.wlan.config('mac')).decode()
     printflush('MAC: %s' % self.mac)
     self.entity_id = ENTITIES[self.mac]
     self.friendly_name = FRIENDLY_NAMES[self.mac]
     printflush('Entity ID: %s; Friendly Name: %s' % (
         self.entity_id, self.friendly_name
     ))
     self.post_path = '/api/states/' + self.entity_id
     printflush('POST path: %s' % self.post_path)
Example #2
0
 def __init__(self, pin):
     self.ow = OneWire(pin)
     # Scan the 1-wire devices, but only keep those which have the
     # correct # first byte in their rom for a DS18x20 device.
     self.roms = [
         rom for rom in self.ow.scan() if rom[0] == 0x10 or rom[0] == 0x28
     ]
    def __init__(self):
        p_pwr1.value(1)

        ow = OneWire(p_DS18B20)  # Pin 13 is the data pin for the DS18B20
        self.ds = DS18X20(ow)  # Initialize a ds18b20 object
        self.roms = self.ds.scan(
        )  # Find all the DS18B20 sensors that are attached (we only have one)
class DS18X20(object):
    def __init__(self, pin):
        self.ow = OneWire(pin)
        # Scan the 1-wire devices, but only keep those which have the
        # correct # first byte in their rom for a DS18x20 device.
        self.roms = [rom for rom in self.ow.scan() if rom[0] == 0x10 or rom[0] == 0x28]

    def read_temp(self, rom=None):
        """
        Read and return the temperature of one DS18x20 device.
        Pass the 8-byte bytes object with the ROM of the specific device you want to read.
        If only one DS18x20 device is attached to the bus you may omit the rom parameter.
        """
        rom = rom or self.roms[0]
        ow = self.ow
        ow.reset()
        ow.select_rom(rom)
        ow.write_byte(0x44)  # Convert Temp
        while True:
            if ow.read_bit():
                break
        ow.reset()
        ow.select_rom(rom)
        ow.write_byte(0xbe)  # Read scratch
        data = ow.read_bytes(9)
        return self.convert_temp(rom[0], data)

    def read_temps(self):
        """
        Read and return the temperatures of all attached DS18x20 devices.
        """
        temps = []
        for rom in self.roms:
            temps.append(self.read_temp(rom))
        return temps

    def convert_temp(self, rom0, data):
        """
        Convert the raw temperature data into degrees celsius and return as a float.
        """
        temp_lsb = data[0]
        temp_msb = data[1]
        if rom0 == 0x10:
            if temp_msb != 0:
                # convert negative number
                temp_read = temp_lsb >> 1 | 0x80  # truncate bit 0 by shifting, fill high bit with 1.
                temp_read = -((~temp_read + 1) & 0xff) # now convert from two's complement
            else:
                temp_read = temp_lsb >> 1  # truncate bit 0 by shifting
            count_remain = data[6]
            count_per_c = data[7]
            temp = temp_read - 0.25 + (count_per_c - count_remain) / count_per_c
            return temp
        elif rom0 == 0x28:
            temp = (temp_msb << 8 | temp_lsb) / 16
            if (temp_msb & 0xf8) == 0xf8: # for negative temperature
                temp -= 0x1000
            return temp
        else:
            assert False
Example #5
0
def temp_init(pin=PIN_TEMP):
    printHead("temp")
    print("dallas temp init >")
    from onewire import OneWire
    from ds18x20 import DS18X20
    dspin = Pin(pin)
    # from util.octopus_lib import bytearrayToHexString
    try:
        ds = DS18X20(OneWire(dspin))
        ts = ds.scan()

        if len(ts) <= 0:
            io_conf['temp'] = False

        for t in ts:
            print(" --{0}".format(bytearrayToHexString(t)))
    except:
        io_conf['temp'] = False
        print("Err.temp")

    print("Found {0} dallas sensors, temp active: {1}".format(
        len(ts), io_conf.get('temp')))

    if len(ts) > 1:
        print(get_temp_n(ds, ts))
    else:
        print(get_temp(ds, ts))

    return ds, ts
Example #6
0
    def __init__(self, internal_sensor_pin, external_sensor_pin):
        self.internal_sensor = DS18X20(OneWire(internal_sensor_pin))

        # scan for devices on the bus
        self.rom = self.internal_sensor.scan()[0]

        self.external_sensor = DHT11(external_sensor_pin)
Example #7
0
    def __prep_pin(self, pin):
        """Prepare pin for OneWire device

        Args:
            pin (int): pin with onewire device
        """
        self.ds = DS18X20(OneWire(Pin(pin)))
        self.dev = self.ds.scan()[0]
Example #8
0
    def __init__(self, unit='C'):

        pin = machine.Pin(18)
        o = OneWire(pin)

        self.d = DS18X20(o)
        self.devicelist = self.d.scan()
        self.unit = unit
Example #9
0
 def __init__(self, pin: int, pause: int = 1, verbose: bool = False):
     self._pin = pin
     self._temperature_sensor = DS18X20(OneWire(Pin(pin)))
     self._temperature_chips = self._temperature_sensor.scan()
     self.pause = pause
     self.is_verbose = verbose
     self.state = dict(temperature=dict())
     print("The sensor controller module started")
Example #10
0
 def __init__(self, postfix, pin, **kwargs):
     super().__init__(postfix, **kwargs)
     self.pin = Pin(pin)
     self.onewire = OneWire(self.pin)
     self.sensor = DS18X20(self.onewire)
     self.roms = self.sensor.scan()
     self.initialized = False  # Sensor conversion takes 700mS, always lag one iteration behind.
     print("Found %d ds18x20 sensor(s)" % len(self.roms))
Example #11
0
def setup():
    global logger, rtc, sd, iCAM, iACC, CTLR_IPADDRESS, logfile, filename
    global wdt, ow, temp, py, sensor

    gc.enable()

    # HW Setup
    wdt = WDT(timeout=wdt_timeout)
    sd = SD()
    rtc = RTC()
    os.mount(sd,'/sd')
    # Enable WiFi Antenna
    Pin('P12', mode=Pin.OUT)(True)

    # TEMPERATURE SENSORS: DS18B20 and SI7006A20
    ow = OneWire(Pin('P10'))
    temp = DS18X20(ow)
    py = Pysense()
    sensor = SI7006A20(py)


    # SYSTEM VARIABLES
    iCAM = pycom.nvs_get('iCAM') # pycom.nvs_set('iCAM',1)
    iACC = pycom.nvs_get('iACC') # pycom.nvs_set('iACC',1)

    logfile='/sd/log/{}.log'.format(datetime_string(time.time()))
    logging.basicConfig(level=logging.DEBUG,filename=logfile)
    logger = logging.getLogger(__name__)

    # # NETWORK VARIABLES
    # pbconf = pybytes.get_config()
    # AP = pbconf['wifi']['ssid']
    # if AP == 'wings':
    #     CTLR_IPADDRESS = '192.168.1.51'
    # elif AP == 'RUT230_7714':
    #     CTLR_IPADDRESS = '192.168.1.100'
    #     # CONNECT TO AP
    #     wlan = WLAN(mode=WLAN.STA)
    #     while not wlan.isconnected():
    #         nets = wlan.scan()
    #         for net in nets:
    #             if net.ssid == 'RUT230_7714':
    #                 pybytes.connect_wifi()
    #
        # wlan.ifconfig(config=('192.168.1.100', '255.255.255.0', '192.168.1.1', '8.8.8.8'))
        # wlan.connect('RUT230_7714', auth=(WLAN.WPA2, 'Ei09UrDg'), timeout=5000)
        # while not wlan.isconnected():
        #     machine.idle() # save power while waiting
    socket_client.CTLR_IPADDRESS = CTLR_IPADDRESS

    # GREETING
    logger.info('--------------------')
    logger.info(' Starting CAM{}-ACC{}'.format(iCAM, iACC))
    logger.info('--------------------')
    logger.info('AP={}'.format(AP))
    gc.collect()

    return
Example #12
0
def DS18B20_func(sens_name, sig_nbr, pin_str, temp_prior):
    #DS18B20 data line connected to pin pin_str
    pin = Pin(pin_str)
    ow = OneWire(pin)
    temp = DS18X20(ow)
    pycom.heartbeat(False)

    print('\n' + sens_name + ' sensor is initialized to ' + pin_str)

    # Prior needs to be within 5 degrees celsius from actual temp
    temperature_prev = temp_prior
    while True:
        temperature = temp.read_temp_async()
        time.sleep(1)
        #time.sleep(DELAY)
        temp.start_conversion()
        time.sleep(1)
        # Remove None values and outliers
        while temperature is None or abs(temperature -
                                         temperature_prev) > OUTLIER_THRESHOLD:
            print(sens_name + ' temperature error: ' + str(temperature))
            # In order to remove the None values I need to reinitialize the sensor
            # it may be a better solution to this
            ow = OneWire(pin)
            temp = DS18X20(ow)
            temperature = temp.read_temp_async()
            time.sleep(1)
            temp.start_conversion()
            time.sleep(1)

        temperature = round(temperature, DECIMALS)
        print(sens_name + ' temperature: ' + str(temperature))

        # Send to pybytes and blink red
        pycom.rgbled(0x330000)
        pybytes.send_signal(sig_nbr, temperature)
        pycom.rgbled(0x000000)

        # Send to ubidots and blink green
        pycom.rgbled(0x003300)
        ubidots_send.post_var("Pycom", sens_name, temperature)
        pycom.rgbled(0x000000)

        temperature_prev = temperature
        time.sleep(DELAY)
 def __init__(self):
     print("Init")
     self.unhandled_event = False
     print('Init LEDs')
     self.leds = {
         'red': Pin(D2, Pin.OUT, value=False),
         'blue': Pin(D3, Pin.OUT, value=False),
         'green': Pin(D4, Pin.OUT, value=False)
     }
     print('Init OneWire')
     self.ds_pin = Pin(D1)
     self.ow_inst = OneWire(self.ds_pin)
     self.ds_sensor = DS18X20(self.ow_inst)
     self.temp_id = self.ds_sensor.scan()[0]
     print('Temperature sensor: %s' % self.temp_id)
     self.wlan = network.WLAN(network.STA_IF)
     self.mac = hexlify(self.wlan.config('mac')).decode()
     print('MAC: %s' % self.mac)
Example #14
0
    def __init__(self, name: str, pin_num: int) -> None:
        """
        Digital temp sensor DS18B20 for the tlvlp.iot project

        Tested on ESP32 MCUs
        :param pin_num: Digital input pin number for reading measurements
        """
        self.reference = "ds18b20|" + name
        one_wire = OneWire(Pin(pin_num))
        self.channel = ds18x20.DS18X20(one_wire)
 def __init__(self, pin):
     """
     Finds addresses of DS18B20 on bus specified by `pin`
     :param pin: 1-Wire bus pin
     :type pin: int
     """
     self.ds = DS18X20(OneWire(Pin(pin)))
     self.addrs = self.ds.scan()
     if not self.addrs:
         raise Exception('no DS18B20 found at bus on pin %d' % pin)
Example #16
0
 def __init__(self, pin):
     """
     Finds address of all DS18B20 on bus specified by `pin`
     :param pin: 1-Wire bus pin
     :type pin: int
     """
     self.ds = ds18x20.DS18X20(OneWire(Pin(pin)))
     addr = self.ds.scan()
     if not addr:
         raise Exception('no DS18B20 found at bus on pin %d' % pin)
Example #17
0
    def __init__(self, pin=32):
        from onewire import OneWire
        from ds18x20 import DS18X20

        self.pin = pin
        self.ts = []
        try:
            self.ds = DS18X20(OneWire(Pin(self.pin)))
            self.ts = self.ds.scan()
        except Exception:
            print("Found {0} dallas sensors, temp active: {1}".format(len(ts), io_conf.get('temp')))
Example #18
0
 def __init__(self, pin):
     """Finds address of single DS18B20 on bus specified by `pin`
     Args:
         pin: 1-Wire bus pin
     """
     self.ds = DS18X20(OneWire(Pin(pin)))
     addrs = self.ds.scan()
     if not addrs:
         raise Exception('no DS18B20 found at bus on pin %d' % pin)
     # save what should be the only address found
     self.addr = addrs.pop()
Example #19
0
    def __init__(self, channel_id, api_key, pin):
        self.channel_id = channel_id
        self.api_key = api_key
        self.ds = DS18X20(OneWire(pin))
        self.sensor = first(self.ds.scan())

        if self.sensor is None:
            raise BrewtrackerError("No temperature sensor available!")

        # Last read sensor value in degrees celsius
        self.value = 0
Example #20
0
    def __init__(self, pin):
        self.check_ticks_ms = 0
        self.ds = DS18X20(OneWire(Pin(pin)))
        self.rom = None
        self.buffer = RingBuffer(6)
        self.state = DS_IDEL

        roms = self.ds.scan()
        if roms:
            self.rom = roms[0]
            UI.LogOut(str(self.rom))
Example #21
0
    def __init__(self, ow_pin, fan_pin):
        ow = OneWire(ow_pin)
        self.ds_sensor = DS18X20(ow)
        self.roms = []

        fan_pin.value(0)
        self.fan_pin = fan_pin
        self.fan_value = 'off'

        self.acc = 0
        self.acc_count = 0
Example #22
0
 def __init__(self, pin=12):
     self.read_count = 0
     self.sensor = 'null'
     self.temp = '85.0' # the default error temperature of ds18b20
     try:
        ow = OneWire(Pin(pin))
        self.ds = ds18x20.DS18X20(ow)
        self.present = True
     except:
        self.present = False
        self.ds = None
Example #23
0
    def __init__(self, config={}):
        self._temp_sens = DS18X20(OneWire(Pin(config.get("pin", 0))))
        self._temp_sens_dev = self._temp_sens.scan()[0]
        self.last_read = time()
        self.state = None
        self.old_state = None

        self.type = config.get('type', "temp_sensor")
        self.topic = config.get('state_topic', None)
        self.set_topic = config.get('command_topic', None)

        self._temp_sens.convert_temp()
Example #24
0
 def __init__(self, pin):
     """
     Finds address of single DS18B20 on bus specified by `pin`
     :param pin: 1-Wire bus pin
     :type pin: int
     """
     self.ds = DS18X20(OneWire(Pin(pin)))
     addrs = self.ds.scan()
     if not addrs:
         raise Exception('no DS18B20 found at bus on pin %d' % pin)
     # save what should be the only address found
     self.addr = addrs.pop()
     print("found one sensor at address:", self.addr)
Example #25
0
 def register_sensor(self):
     if self.pin > 16 or self.pin < 0:
         raise Exception('Invalid GPIO {}'.format(self.pin))
     if self.sensor_model == "DHT11":
         self.sensor_handle = dht.DHT11(Pin(self.pin))
     elif self.sensor_model == "DHT22":
         self.sensor_handle = dht.DHT22(Pin(self.pin))
     elif self.sensor_model == 'DS18B20':
         self.sensor_handle = DS18X20(OneWire(self.pin))
         self.sensor_handle.convert_temp()
     elif self.sensor_model == 'SWITCH':
         self.sensor_handle = Pin(self.pin, Pin.IN, Pin.PULL_UP)
     return True
 def __init__(self, pin=12):
     self.count = 0
     self.sensor = 'null'
     self.temp = '85.0' # the default error temperature of ds18b20
     try:
         ow = OneWire(Pin(pin))
         self.ds = ds18x20.DS18X20(ow)
         self.roms = self.ds.scan() # should we scan again?
         self.ds.convert_temp()
         time.sleep_ms(750)
         self.temp = self.ds.read_temp(self.roms[1])
         self.present = True
     except:
         self.present = False
         self.ds = None
Example #27
0
    def __init__(self, motion_pin, micro_pin, pixel_pin, pixels, temp_pin):
        self.motion = 'OFF'
        self.motion_timer = Timer(-1)
        self.temp_timer = Timer(-2)
        self.temperature = None
        self.one_wire = DS18X20(OneWire(Pin(temp_pin)))
        self.temp_sensor = None  # initiated in function temp_sensor
        self.micro_sensor = Pin(micro_pin, Pin.IN)
        self.micro_sensor.irq(handler=self.micro_high, trigger=Pin.IRQ_RISING)
        self.motion_sensor = Pin(motion_pin, Pin.IN)
        self.motion_sensor.irq(handler=self.motion_high,
                               trigger=Pin.IRQ_RISING)
        self.pixels = NeoPixel(Pin(pixel_pin), pixels)
        self.lastmotion = time()

        self.temp_sensor_init()
Example #28
0
 def __init__(self, pin):
     if not isinstance(pin, int):
         raise TypeError("pin must be integer")
     from onewire import OneWire
     from ds18x20 import DS18X20
     ow = OneWire(machine.Pin(pin))
     ow.scan()
     ow.reset()
     self.ds18b20 = DS18X20(ow)
     self.roms = self.ds18b20.scan()
     self.temps = [None for rom in self.roms]
def daemon():
    """ Measure the temperature at fixed intervals """
    ds = DS18X20(OneWire(Pin.exp_board.G9))
    t = 0.0

    while True:
        # measure +- every 30 seconds
        time.sleep(27)
        for i, tx in enumerate([t0, t1]):
            time.sleep_ms(750)
            ds.start_conversion(ds.roms[i])
            time.sleep_ms(750)
            t = ds.read_temp_async(ds.roms[i])
            with t_lock:
                tx.append(t)
                if len(tx) > NMEASUREMENTS:
                    del tx[0]
Example #30
0
def get_data_ds18b20(pin_nr):
    ds_pin = machine.Pin(pin_nr)
    ds_sensor = DS18X20(OneWire(ds_pin))

    roms = ds_sensor.scan()

    if not roms:
        return None

    ds_sensor.convert_temp()
    utime.sleep_ms(750)  # give enough time to convert the temperature

    temperature = None

    for rom in roms:
        temperature = ds_sensor.read_temp(rom)

    return {'temperature': temperature, 'humidity': None}
Example #31
0
from ds18b20 import DS18B20
import utils
try:
    import config
except:
    pyb.LED(4).on()
import variables

IS_START = True

PACK_SYNC = 1
PACK_COMMAND = 2
PACK_ERROR = 3

# Инициализация шин
ow = OneWire('Y12')
DS18B20(ow).start_measure()
rs485 = RS485(3, 'Y11', dev_id=1)

# Создаем драйвера для переменных сети OneWire и передаем им экземпляр OW.
variables.set_variable_drivers(ow, rs485.dev_id)

# Отбираем отдельный список термометров
termometrs = []
for driver in variables.driverList:
    if driver and driver.rom and (driver.rom[0] == 0x28):
        termometrs += [driver]

# Создаем специальный таймер для синхронизации обновлений термометров.
timer_1_flag = False
def timer_1_handler(timer):
Example #32
0
 def __init__(self, pin):
     self.ow = OneWire(pin)
     # Scan the 1-wire devices, but only keep those which have the
     # correct # first byte in their rom for a DS18x20 device.
     self.roms = [rom for rom in self.ow.scan() if rom[0] == 0x10 or rom[0] == 0x28]