Пример #1
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]
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
Пример #3
0
class TemperatureSensor:
    class _Const:
        CONVERT = const(0x44)
        RD_SCRATCH = const(0xbe)
    
    def __init__(self, pin):
        self._onewire = OneWire(pin)
        self._buffer = bytearray(9)
        self._rom = [rom for rom in self._onewire.scan() if rom[0] in (0x10, 0x22, 0x28)][0]
        self._convert_temp()

    def _convert_temp(self):
        self._onewire.reset(True)
        self._onewire.writebyte(self._onewire.SKIP_ROM)
        self._onewire.writebyte(self._Const.CONVERT)

    def _read_scratch(self):
        self._onewire.reset(True)
        self._onewire.select_rom(self._rom)
        self._onewire.writebyte(TemperatureSensor._Const.RD_SCRATCH)
        self._onewire.readinto(self._buffer)
        if self._onewire.crc8(self._buffer):
            raise Exception('Temperature sensor::CRC error')
        
        return self._buffer

    def read(self):
        buffer = self._read_scratch()
        if self._rom[0] == 0x10:
            if self._buffer[1]:
                t = self._buffer[0] >> 1 | 0x80
                t = -((~t + 1) & 0xff)
            else:
                t = self._buffer[0] >> 1
            
            return t - 0.25 + (self._buffer[7] - self._buffer[6]) / self._buffer[7]
        else:
            t = self._buffer[1] << 8 | self._buffer[0]
            if t & 0x8000:
                t = -((t ^ 0xffff) + 1)
            
            return t / 16
Пример #4
0
#                        "very_low":20,"low":25,"medium":30,"high":35,"very_high":40,"extreme":45 },
#                      "Hot_Isle" : {
#                        "very_low":20,"low":25,"medium":30,"high":35,"very_high":40,"extreme":45 },
                      "Exhaust" : {
                        "very_low":20,"low":25,"medium":30,"high":35,"very_high":40,"extreme":45 }
                    }
#Fan RPM Speeds.
fan_rpm_speeds = { "very_low":30, "low":40, "medium":50, "high":60, "very_high":80, "extreme":100 }

#########################################
# CHECK 1-WIRE BUS
#########################################

# Scan the 1-Wire bus and find available devices
print('Scanning the One Wire Bus....')
devices = ow.scan()
num_devices_found=len(devices)
#for key in devices:
#    device_serial="".join("%02x" % key[c-1] for c in range(len(key), 0, -1))
#    print("  * ",device_serial)

# Check to see if the sensors expected are available.
print('Looking for the following devices....')
for key in temp_sensors:
  sensor_found="Missing"
  if temp_sensors[key]["serial"] in devices:
    sensor_found="Available"
    temp_sensors[key]["available"]=1
  device_serial="".join("%02x" % temp_sensors[key]["serial"][c-1] for c in range(len(temp_sensors[key]["serial"]), 0, -1))
  #device_serial=NASTemp.convert_serial(temp_sensors[key]["serial"])
  print("  * "+key+" Serial Number = "+device_serial+" ("+sensor_found+")")
Пример #5
0
    print("Tempo apos inicializaco LoRA: {} ms".format(lap2))

#
# Inicialização e leitura dos sensores
#
if flagRun:
    lap1 = chrono.read_ms()

i2c = I2C(0, I2C.MASTER, pins=('G10', 'G9'), baudrate=400000)
connectedI2C = i2c.scan()
if flagDebug:
    print("Connected I2C devices: " + str(connectedI2C))

ow = OneWire(Pin('G8'))
temp = DS18X20(ow)
connectedOW = ow.scan()
if flagDebug:
    print("Connected 1-Wire devices: " + str(connectedOW))

ilum = []  # Lista com as luminosidades lidas com o MAX44009
bmet = []  # Lista com as temperaturas lidas com o BME280
bmeh = []  # Lista com as umiadades lidas com o BME280
bmep = []  # Lista com as pressoes lidas com o BME280
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
Пример #6
0
 def getaddr(self):
     ow = OneWire(Pin(self.pin))
     a = ow.scan()
     for i in a:
         self.no_addr += 1
     return a
Пример #7
0
led2 = pyb.LED(2)
led3 = pyb.LED(3)
led4 = pyb.LED(4)
led1.on()
gnd = pyb.Pin('Y11', pyb.Pin.OUT_PP)
gnd.low()
vcc = pyb.Pin('Y9', pyb.Pin.OUT_PP)
vcc.high()
d = DS18X20(pyb.Pin('Y10'))
o = OneWire(pyb.Pin('Y10'))

mp = pyb.USB_VCP()

led1.off()

while (1):
    led4.on()
    mydict = {}
    # For backwards compatibility keep this one
    mydict['temperature'] = d.read_temp()
    devicelist = o.scan()
    tempdict = {}
    led4.off()
    for device in devicelist:
        tempdict[ubinascii.hexlify(device)] = d.read_temp(device)
    mydict['devicelist'] = tempdict
    mystr = json.dumps(mydict)
    mp.write(mystr)
    mp.write('\n')
    time.sleep(0.1)
Пример #8
0
# you need to specify the ROM address of the sensor as well
# If only one DS18x20 device is attached to the bus you may omit the rom parameter.
def measureTemperature(owBus,rom=None):
    while True: # we loop until we get a valid measurement
        temp = DS18X20(owBus)
        temp.start_conversion(rom)
        time.sleep(1) # wait for one second
        TempCelsius=temp.read_temp_async(rom)
        if TempCelsius is not None:
            return TempCelsius # TempCelsius exit loop and return result

# single temperature measurement omitting the ROM parameter
SensorTempCelsius=measureTemperature(ow)
print("Temperature (degrees C) = %7.1f" % SensorTempCelsius)

# Each DS18X20 has a unique 64-bit (=8 bytes) address in its ROM memory
# (ROM = read only memory)
# When one or several DS18XB20 are connected to the same onewire bus, we can
# get their ROM addresses in the following way:
roms=ow.scan() # returns a list of bytearrays
for rom in roms: # we loop over the elements of the list
    print('ROM address of DS18XB20 = ',ubinascii.hexlify(rom))# hexlify to show
    # bytearray in hex format

# The following loop measures temperature continuously, looping over all
# sensors as well
while True: # loop forever (stop with ctrl+C)
     for rom in roms: # we loop over the elements of the list, i.e. we loop over
        # the detected DS18XB20 sensors
        print("For DS18XB20 with ROM address =", ubinascii.hexlify(rom), "the temperature (degrees C) = %7.1f" % measureTemperature(ow,rom))