示例#1
0
class RaspiI2cLogger(object):
    def __init__(self):
        self.i2c = SMBus(1)
        self.address = 0x48
        self.block = None

    def is_address_exist(self):
        try:
            time.sleep(1)
            self.block = self.i2c.read_i2c_block_data(self.address, 0x00, 2)
        except OSError as e:
            print("Oops...  change address...")

            if self.address == 0x48:
                self.address = 0x49
                print("change address to 0x49")
                return False
            elif self.address == 0x49:
                self.address = 0x4b
                print("change address to 0x4b")
                return False
            else:
                self.address = 0x48
                print("change address to 0x48")
                return False

        return True

    def get_temperature(self):
        iteration = 0
        if self.is_address_exist():
            val = self.block[0] << 8
            val = val | self.block[1]
            val = val >> 3

            if (val >= 4096):
                val = val - 8192

            print("TEMPerature:" + str(val / 16.0))
            return (val / 16.0)
        else:
            print("using invalid address")
            iteration += 1
            print(iteration)
            return self.get_temperature()

    def logging(self, time_interval=5):
        while True:
            print(self.get_temperature())
            #for notifing to slack
            #slack = slackweb.Slack(url=inifile.get("slack", "webhook_url"))
            #slack.notify(text=str(val/16.0))
            #attachments = []
            #attachment = {"title": "raspi_temperature", "pretext": "location_1", "text": str(val/16.0)}
            #attachments.append(attachment)
            #slack.notify(attachments=attachments)

            #time.sleep(1)
            #time.sleep(599)
            time.sleep(time_interval)
示例#2
0
class I2C(object):
    """
	This is just a wrapper around i2c. There are so many implementations.
	"""
    def __init__(self, address, bus=1):
        self.i2c = SMBus(bus)
        self.address = address

    def __del__(self):
        self.i2c.close()

    def read8(self, reg):
        b = self.i2c.read_byte_data(self.address, reg)
        return b

    def read_block(self, reg, size):
        block = self.i2c.read_i2c_block_data(self.address, reg, size)
        return block

    def write_block(self, reg, data):
        self.i2c.write_i2c_block_data(self.address, reg, data)

    def write8(self, reg, data):
        # print(hex(self.address), reg, data)
        self.i2c.write_byte_data(self.address, reg, data)
示例#3
0
    def test_read(self):
        res = []
        res2 = []
        res3 = []

        bus = SMBus(1)

        # Read bytes
        for k in range(2):
            x = bus.read_byte_data(80, k)
            res.append(x)
        self.assertEqual(len(res), 2, msg="Result array of incorrect length.")

        # Read word
        x = bus.read_word_data(80, 0)
        res2.append(x & 255)
        res2.append(x / 256)
        self.assertEqual(len(res2), 2, msg="Result array of incorrect length.")
        self.assertListEqual(res, res2, msg="Byte and word reads differ")

        # Read block of N bytes
        n = 2
        x = bus.read_i2c_block_data(80, 0, n)
        res3.extend(x)
        self.assertEqual(len(res3), n, msg="Result array of incorrect length.")
        self.assertListEqual(res, res3, msg="Byte and block reads differ")

        bus.close()
示例#4
0
    def test_read(self):
        res = []
        res2 = []
        res3 = []

        bus = SMBus(1)

        # Read bytes
        for k in range(2):
            x = bus.read_byte_data(80, k)
            res.append(x)
        self.assertEqual(len(res), 2, msg="Result array of incorrect length.")

        # Read word
        x = bus.read_word_data(80, 0)
        res2.append(x & 255)
        res2.append(x / 256)
        self.assertEqual(len(res2), 2, msg="Result array of incorrect length.")
        self.assertListEqual(res, res2, msg="Byte and word reads differ")

        # Read block of N bytes
        n = 2
        x = bus.read_i2c_block_data(80, 0, n)
        res3.extend(x)
        self.assertEqual(len(res3), n, msg="Result array of incorrect length.")
        self.assertListEqual(res, res3, msg="Byte and block reads differ")

        bus.close()
示例#5
0
def read_eeprom():
    """Return a class representing EEPROM contents, or none."""
    try:
        i2c = SMBus(1)
        i2c.write_i2c_block_data(EEP_ADRESS, 0x00, [0x00])
        return EPDType.from_bytes(i2c.read_i2c_block_data(0x50, 0, 29))
    except IOError:
        return None
示例#6
0
class Tsl2561Sensor(RestoreEntity):
    """Representation of a Sensor."""

    def __init__(self):
        """Initialize the sensor."""
        self._state = None
        self._bus = SMBus(1)

    @property
    def name(self):
        """Return the name of the sensor."""
        return 'Luminosita'

    @property
    def state(self):
        """Return the state of the sensor."""
        return self._state

    @property
    def unit_of_measurement(self):
        """Return the unit of measurement."""
        return "lux"

    def update(self):
        """Fetch new state data for the sensor."""
        self._state = self._lightcheck()

    def _lightcheck(self):
        self._bus.write_byte(TSLaddr, 0x00 | TSLcmd, TSLon) #Power On
        #Gain x1 at 402ms is the default so this line not required but change for different sensitivity
        self._bus.write_byte(TSLaddr, 0x01 | TSLcmd,LowLong) #Gain x1 402ms

        time.sleep(1) #give time sensor to settle

        #Read Ch0 Word
        data = self._bus.read_i2c_block_data(TSLaddr, chan0 | TSLcmd, 2)
        #Read CH1 Word
        data1 = self._bus.read_i2c_block_data(TSLaddr, chan1 | TSLcmd, 2)

        # Convert the data to Integer
        ch0 = data[1] * 256 + data[0]
        ch1 = data1[1] * 256 + data1[0]
        vResults = ch0-ch1 #get visable light results
        self._bus.write_byte(TSLaddr, 0x00 | TSLcmd, TSLoff) #switch off

        return str(vResults)
示例#7
0
class MCP9808:
    def __init__(self, bus, addr, resolution=0x03):
        self.addr = addr
        self.res = resolution
        self.bus = SMBus(bus)
        self.init()

    # Initialise the MCP9808 with resolution for continuous readings
    def init(self):
        # Write config
        config = [0x00, 0x00]
        self.bus.write_i2c_block_data(self.addr, 0x01, config)
        # Write resolution
        if ((self.res > 0x03) or (self.res < 0)):
            self.res = 0x03
        self.bus.write_byte_data(self.addr, 0x08, self.res)
        # Read Device ID/Revision register
        rid = self.bus.read_byte_data(self.addr, 0x07)
        tmp = self.bus.read_i2c_block_data(self.addr, 0x06, 2)
        mid = ((tmp[0] & 0x1F) * 256) + tmp[1]
        #print "Init MCP9808 Manufacurer ID: 0x{:04x}, Device ID: 0x{:02x}".format(mid, rid)

    # Obtain temperature reading
    def t_read(self):
        # Final celcius temp
        ctemp = 0.0
        # Obtain temp reading in binary
        tin = self.bus.read_i2c_block_data(self.addr, 0x05, 2)
        bt = ((tin[0] & 0x1F) * 256) + tin[1]
        # Check if two's comp
        if (bt > 4095):
            bt -= 8192
        # Multiply by resolution
        if (self.res == 0x00):
            ctemp = bt * 0.5
        elif (self.res == 0x01):
            ctemp = bt * 0.25
        elif (self.res == 0x02):
            ctemp = bt * 0.125
        elif (self.res == 0x03):
            ctemp = bt * 0.0625
        else:
            ctemp = bt * 0.0625
        # Round and format
        return "{:.2f}".format(round(ctemp, 2))
示例#8
0
class FlowSensor:
    def __init__(self):
        self.bus = SMBus(1)

    @property
    def data(self):
        data = self.bus.read_i2c_block_data(0x07, 0, 2)
        flow = ((data[0] << 8) + data[1]) / 1000  # LPM
        return flow
示例#9
0
class HTU21D:
    def __init__(self, busno):
        self.bus = SMBus(busno)

    def read_temperature(self):
        self.reset()
        msb, lsb, crc = self.bus.read_i2c_block_data(I2C_ADDR,
                                                     CMD_TRIG_TEMP_HM, 3)
        return -46.85 + 175.72 * (msb * 256 + lsb) / 65536

    def read_humidity(self):
        self.reset()
        msb, lsb, crc = self.bus.read_i2c_block_data(I2C_ADDR,
                                                     CMD_TRIG_HUMID_HM, 3)
        return -6 + 125 * (msb * 256 + lsb) / 65536.0

    def reset(self):
        self.bus.write_byte(I2C_ADDR, CMD_RESET)
示例#10
0
class AMG88XX:
    # AMG8833 specs
    AMG8833_PIXEL_ARRAY_WIDTH = 8
    AMG8833_PIXEL_ARRAY_HEIGHT = 8
    AMG8833_PIXEL_TEMP_CONVERSION = 0.25
    AMG8833_THERMISTOR_CONVERSION = 0.0625
    AMG8833_MIN_TEMP = 22
    AMG8833_MAX_TEMP = 32.0

    def __init__(self, bus=1, address=0x69):
        self._address = address
        self._bus = SMBus(bus)

        self.write(AMG88XX_PCTL, AMG88XX_NORMAL_MODE)
        self.write(AMG88XX_RST, AMG88XX_INITIAL_RESET)
        self.write_bit(AMG88XX_INTC, AMG88XX_INTEN_bit, AMG88XX_INT_DISABLED)
        self.write_bit(AMG88XX_FPSC, AMG88XX_FPS_bit, AMG88XX_FPS_10)

    # ----------------------------- I2C  Utilites -----------------------------#
    def write(self, register, data):
        self._bus.write_byte_data(self._address, register, data)
        time.sleep(0.0001)

    def write_bit(self, register, bit, val):
        bitmask = (val & 0b1) << bit
        data = self._bus.read_byte_data(self._address, register)
        data |= bitmask
        self._bus.write_byte_data(self._address, register, data)

    def read(self, register):
        return self._bus.read_byte_data(self._address, register)

    def read_bytes(self, register, num_bytes):
        return self._bus.read_i2c_block_data(self._address, register, num_bytes)

    # ------------------------------- AMG8833  --------------------------------#
    def get_temperature(self):
        """Temperature of the sensor in Celsius"""
        raw = (self.read(AMG88XX_TTHH << 8)) | self.read(AMG88XX_TTHL)
        return _signed_12bit_to_float(raw) * self.AMG8833_THERMISTOR_CONVERSION

    def get_pixels(self):
        """Temperature of each pixel across the sensor in Celsius.
           Temperatures are stored in a two dimensional list where the first index is the row and
           the second is the column. The first row is on the side closest to the writing on the
           sensor."""
        pixels = [[0] * self.AMG8833_PIXEL_ARRAY_WIDTH for _ in range(self.AMG8833_PIXEL_ARRAY_HEIGHT)]

        for row in range(self.AMG8833_PIXEL_ARRAY_HEIGHT):
            for col in range(self.AMG8833_PIXEL_ARRAY_WIDTH):
                reg = AMG88XX_PIXEL_OFFSET + ((row * self.AMG8833_PIXEL_ARRAY_HEIGHT + col) << 1)
                raw = self.read_bytes(reg, 2)
                reading = raw[1] << 8 | raw[0]
                pixels[row][col] = _twos_comp_to_float(reading) * self.AMG8833_PIXEL_TEMP_CONVERSION

        return pixels
class VCNL4010:
    """Vishay VCNL4010 proximity and ambient light sensor."""
    def __init__(self):
        self._device = SMBus(1)
        self.led_current = 20
        self.frequency = FREQUENCY_390K625
        self._write_u8(_VCNL4010_INTCONTROL, 0x08)

    def _read_u8(self, address):
        # Read an 8-bit unsigned value from the specified 8-bit address.
        with SMBus(1) as self._device:
            read = self._device.read_byte_data(_VCNL4010_I2CADDR_DEFAULT,
                                               address)
        return read

    def _write_u8(self, address, val):
        # Write an 8-bit unsigned value to the specified 8-bit address.
        with SMBus(1) as self._device:
            self._device.write_byte_data(_VCNL4010_I2CADDR_DEFAULT, address,
                                         val)

    def _read_u16BE(self, address):
        with SMBus(1) as self._device:
            read_block = self._device.read_i2c_block_data(
                _VCNL4010_I2CADDR_DEFAULT, address, 2)
        return (read_block[0] << 8) | read_block[1]

    @property
    def proximity(self):
        """The detected proximity of an object in front of the sensor.  This
        is a unit-less unsigned 16-bit value (0-65535) INVERSELY proportional
        to the distance of an object in front of the sensor (up to a max of
        ~200mm).  For example a value of 10 is an object farther away than a
        value of 1000.  Note there is no conversion from this value to absolute
        distance possible, you can only make relative comparisons.
        """
        # Clear interrupt.
        status = self._read_u8(_VCNL4010_INTSTAT)
        status &= ~0x80
        self._write_u8(_VCNL4010_INTSTAT, status)
        # Grab a proximity measurement.
        self._write_u8(_VCNL4010_COMMAND, _VCNL4010_MEASUREPROXIMITY)
        # Wait for result, then read and return the 16-bit value.
        while True:
            result = self._read_u8(_VCNL4010_COMMAND)
            if result & _VCNL4010_PROXIMITYREADY:
                highbyte = self._read_u8(0x87)
                highbyte = format(highbyte, '08b')

                lowbyte = self._read_u8(0x88)
                lowbyte = format(lowbyte, '08b')

                message = highbyte + lowbyte

                return message
示例#12
0
class MeasureLux():
    def __init__(self):
        self.lux = 0

        # Define some constants from the datasheet
        self.DEVICE = 0x23  # Default device I2C address

        self.POWER_DOWN = 0x00  # No active state
        self.POWER_ON = 0x01  # Power on
        self.RESET = 0x07  # Reset data register value

        # Start measurement at 4lx resolution. Time typically 16ms.
        self.CONTINUOUS_LOW_RES_MODE = 0x13
        # Start measurement at 1lx resolution. Time typically 120ms
        self.CONTINUOUS_HIGH_RES_MODE_1 = 0x10
        # Start measurement at 0.5lx resolution. Time typically 120ms
        self.CONTINUOUS_HIGH_RES_MODE_2 = 0x11
        # Start measurement at 1lx resolution. Time typically 120ms
        # Device is automatically set to Power Down after measurement.
        self.ONE_TIME_HIGH_RES_MODE_1 = 0x20
        # Start measurement at 0.5lx resolution. Time typically 120ms
        # Device is automatically set to Power Down after measurement.
        self.ONE_TIME_HIGH_RES_MODE_2 = 0x21
        # Start measurement at 1lx resolution. Time typically 120ms
        # Device is automatically set to Power Down after measurement.
        self.ONE_TIME_LOW_RES_MODE = 0x23

        #bus = smbus.SMBus(0) # Rev 1 Pi uses 0
        #self.bus = SMBus(1)  # Rev 2 Pi uses 1

    def convertToNumber(self, data):
        # Simple function to convert 2 bytes of data
        # into a decimal number. Optional parameter 'decimals'
        # will round to specified number of decimal places.
        # result=(data[1] + (256 * data[0])) / 1.2. window influence 고려하여 0.4 나누기로 수정
        result = (data[1] + (256 * data[0])) / 0.51
        return (result)

    def readLight(self):
        # Read data from I2C interface
        self.bus = SMBus(1)  # Rev 2 Pi uses 1
        addr = self.DEVICE
        data = self.bus.read_i2c_block_data(addr,
                                            self.ONE_TIME_HIGH_RES_MODE_1, 2)
        return self.convertToNumber(data)

    def measureLux(self):
        self.lux = int(self.readLight())
        #print("측정된 조도 : " + format(self.lux,'.2f') + " lx")
        #time.sleep(0.5)
        return self.lux
        if self.stop_threads:
            raise CustomException.MeasureLuxTerminate
示例#13
0
class Lidar_Lite():
    def __init__(self, bus):
        self.bus = SMBus(bus)
        self.address = 0x62
        self.distWriteReg = 0x00
        self.distWriteVal = 0x04
        self.distReadReg1 = 0x8f
        self.distReadReg2 = 0x10
        self.velWriteReg = 0x04
        self.velWriteVal = 0x08
        self.velReadReg = 0x09
        self.updateTime = 0.005

    """
  def connect(self, bus):
    try:
      self.bus = SMBus(bus)
      time.sleep(0.5)
      return 0
    except:
      return -1
  """

    def writeAndWait(self, register, value):
        self.bus.write_byte_data(self.address, register, value)
        time.sleep(self.updateTime)

    def readAndWait(self, register):
        res = self.bus.read_byte_data(self.address, register)
        time.sleep(self.updateTime)
        return res

    def readDistAndWait(self, register):
        res = self.bus.read_i2c_block_data(self.address, register, 2)
        time.sleep(self.updateTime)
        return (res[0] << 8 | res[1])

    def getDistance(self):
        self.writeAndWait(self.distWriteReg, self.distWriteVal)
        dist = self.readDistAndWait(self.distReadReg1)
        return dist

    def getVelocity(self):
        self.writeAndWait(self.distWriteReg, self.distWriteVal)
        self.writeAndWait(self.velWriteReg, self.velWriteVal)
        vel = self.readAndWait(self.velReadReg)
        return self.signedInt(vel)

    def signedInt(self, value):
        if value > 127:
            return (256 - value) * (-1)
        else:
            return value
示例#14
0
    class I2CBus():
        def __init__(self, I2C_bus_number, address):
            self.bus = SMBus(I2C_bus_number)
            self.address = address

        def write_register(self, reg_address, device_address=None):
            device_address = self.address
            return self.bus.write_byte(device_address, reg_address)

        def read_registers(self, reg_address, device_address=None):
            device_address = self.address
            return self.bus.read_i2c_block_data(device_address, reg_address, 6)
示例#15
0
def getTempAndHumidityData():
    import time
    from smbus2 import SMBus
    SHT31_ADDRESS = 0x45
    bus = SMBus(1)
    bus.write_i2c_block_data(SHT31_ADDRESS, 0x2C, [0x06])
    time.sleep(0.25)
    data = bus.read_i2c_block_data(SHT31_ADDRESS, 0x00, 6)
    bus.close()
    rawTemp = data[0] * 256 + data[1]
    temp = -45 + (175 * rawTemp / 65535.0)
    humidity = 100 * (data[3] * 256 + data[4]) / 65535.0
    return temp, humidity
示例#16
0
class Encoder:

    def __init__(self, address, bus=1, invert=False):

        self.bus = SMBus(bus)
        self.address = address
        self.invert = invert
        self.resolution = ((math.pi*2)/2**14)                               # Define encoder angular resolution.
        self.position = self.readPos()                                      # Read position of encoder
        self.angle = self.readAngle()
        self.magnitude = self.readMagnitude()

    def readPos(self):

        pos = self.bus.read_i2c_block_data(self.address, 0xFE, 2)           # Request data from registers 0xFE & 0xFF of the encoder
                                                                            # Takes ~700 microseconds.
        if not self.invert:
            self.position = (pos[0] << 6) | pos[1]                          # Remove unused bits 6 & 7 from byte 0xFF creating 14 bit value
        else:
            self.position = (2**14)-((pos[0] << 6) | pos[1])                # Remove unused bits 6 & 7 from byte 0xFF creating 14 bit value & invert the value

        return self.position                                                # Return Raw encoder position (0 to 16384)

    def readAngle(self):

        self.readPos()                                                      # Read encoder position

        self.angle = self.position * (360 / 2**14)                          # Scale values to get degrees

        return self.angle                                                   # Return encoder angle (0 to 359.97802734375)

    def readMagnitude(self):

        magnitude = self.bus.read_i2c_block_data(self.address, 0xFC, 2)     # Request data from registers 0xFC & 0xFD of the encoder
                                                                            # Takes ~700 microseconds.

        self.magnitude = (magnitude[0] << 6) | magnitude[1]                 # Remove unused bits 6 & 7 from byte 0xFD creating 14 bit value

        return self.magnitude                                               # Return encoder magnitude
示例#17
0
文件: eeprom.py 项目: pimoroni/inky
def read_eeprom(i2c_bus=None):
    """Return a class representing EEPROM contents, or none."""
    try:
        if i2c_bus is None:
            try:
                from smbus2 import SMBus
            except ImportError:
                raise ImportError('This library requires the smbus2 module\nInstall with: sudo pip install smbus2')
            i2c_bus = SMBus(1)
        i2c_bus.write_i2c_block_data(EEP_ADDRESS, 0x00, [0x00])
        return EPDType.from_bytes(i2c_bus.read_i2c_block_data(EEP_ADDRESS, 0, 29))
    except IOError:
        return None
示例#18
0
class MAX11644(object):
    def __init__(self, bus=_DEFAULT_BUS, address=_DEFAULT_ADDRESS, internal_reference=True,
                 v_ref_internal=_V_REF_INTERNAL):
        # I2C bus object
        self._i2c = SMBus(bus)
        # added to avoid communication problems
        time.sleep(1)
        self._address = address
        self._SETUP = 0x80
        self._CONF = 0x00

        if internal_reference:
            self._SETUP = 0xD0
            self._ref_volt = v_ref_internal
        else:
            self._SETUP = 0x82
            self._ref_volt = _VDD

        self._SETUP = (self._SETUP | 0x02)  # internal clock, unipolar, no action
        self._send_data_(self._SETUP)

    def _send_data_(self, byte):
        """Send a byte to device"""
        self._i2c.write_byte(self._address, byte)
        time.sleep(0.1)

    def _read_data(self, address):
        """Read 2 bytes from address address."""
        data = self._i2c.read_i2c_block_data(self._address, address, 2)
        return data

    def get_value(self, channel=0):
        """Get Full scale value (12 bits)"""
        if channel == 0:
            self._CONF = 0x61
            data = self._read_data(self._CONF)

        elif channel == 1:
            self._CONF = 0x63
            data = self._read_data(self._CONF)
        else:
            raise Exception("Channel doesn't exist")
        data = ((data[0] & 0x0F) << 8) | data[1]
        return data

    def convert_to_volt(self, value):
        """Convert Full scale value (12 bits) into volts"""
        return self._ref_volt * value / 4096.

    def get_voltage(self, channel=0, factor=1):
        return self.convert_to_volt(self.get_value(channel) / factor)
示例#19
0
    def task(self):
        t_voc = 99999
        try:
            bus = SMBus(I2CBUS)
            bus.write_byte_data(self.I2Caddr, SGP30_MSB, SGP30_MEASURE)
            time.sleep(0.02)
            resp = bus.read_i2c_block_data(self.I2Caddr, 0, 6)
            #read = i2c_msg.read( self.I2Caddr, 6 )
            #bus.i2c_rdwr(read)
            #resp = list(read)

            bus.close()
            # Only care about tVOC since eCO2 is just that
            # bytes 0-2 are eCO2 + CRC8
            # bytes 3-5 are tVOC + CRC8
            temp = [resp[3], resp[4], resp[5]]
            if (self.crc8(temp) == 0):
                t_voc = (resp[3] << 8) | resp[4]

                # maintain 1 minute moving average buffer
                self.voc_buff[self.voc_ptr] = t_voc

                # every 20 seconds write to file system
                if (self.voc_ptr % 20 == 0):
                    # calculate current average voc value
                    # 60 samples per minute
                    avg_voc = 0
                    for i in range(SGP30_MAX):
                        avg_voc += self.voc_buff[i]
                    avg_voc /= SGP30_MAX_FLOAT
                    avg_voc = int(round(avg_voc))

                    print "sgp30.task() voc: %d avg: %d " % (t_voc, avg_voc)

                    f = open(self.FptrVoc, "w")
                    f.write("%d" % avg_voc)
                    f.close()

                self.voc_ptr += 1
                if self.voc_ptr >= SGP30_MAX:
                    self.voc_ptr = 0

        except:
            bus.close()
            print "sgp30.task() failed"

        # returning latest value, not average
        return t_voc
示例#20
0
    def get_baseline(self):
        try:
            # eCO2 baseline word first + crc
            # tVOC baseline word second + crc
            # these two lists need to be in reverse order for setting baseline
            bus = SMBus(I2CBUS)
            bus.write_byte_data(self.I2Caddr, SGP30_MSB, SGP30_GET_BASE)
            time.sleep(0.02)

            # for some reason an extra null byte is needed to get data
            resp = bus.read_i2c_block_data(self.I2Caddr, 0, 6)
            # below doesn't work
            #read = i2c_msg.read( selfI2Caddr, 6 )
            #bus.i2c_rdwr(read)
            #resp = list(read)
            bus.close()

            # Because there are two set of baselines we will just
            # write them directly to the file-system instead of
            # looking for changes
            baseline_co2 = [resp[0], resp[1], resp[2]]
            baseline_voc = [resp[3], resp[4], resp[5]]

            if (self.crc8(baseline_co2) == 0):
                # comma delimited output
                #msg = str(baseline_co2).strip('[]')
                bl = (resp[0] << 8) | resp[1]
                f = open(self.FptrBaseC, "w")
                f.write("%d" % bl)
                f.close()

                print "sgp30.get_baseline() co2: 0x%04x" % bl

            if (self.crc8(baseline_voc) == 0):
                # comma delimited output
                #msg = str(baseline_voc).strip('[]')
                bl = (resp[3] << 8) | resp[4]
                f = open(self.FptrBaseV, "w")
                f.write("%d" % bl)
                f.close()

                print "sgp30.get_baseline() voc: 0x%04x" % bl

        except:
            bus.close()
            print "sgp30.get_baseline() failed"
示例#21
0
class RaspberryI2c(I2c):
    '''@brief version to actually use the I2C bus
    '''
    def __init__(self, bus_id):
        '''@brief constructor
        '''
        super(RaspberryI2c, self).__init__(bus_id)
        from smbus2 import SMBus
        self._bus = SMBus(bus='/dev/i2c-%d' % bus_id)

    def _write(self, address, register, data):
        self._bus.write_i2c_block_data(address, register, data)

    def _read(self, address, register, length):
        return bytes(self._bus.read_i2c_block_data(address, register, length))

    def _close(self):
        self._bus.close()
示例#22
0
def read_arduino(slave_addr, sensor_type):
    try:
        I2Cbus = SMBus(BUS)
        # byte = convert_bytes_to_list(bytes(str(sensor_type), "utf-8"))
        byte = int(sensor_type)
        # I2Cbus.write_i2c_block_data(slave_addr, MEMORY_ADDR, byte)
        I2Cbus.write_byte_data(slave_addr, MEMORY_ADDR, byte)
        response = I2Cbus.read_i2c_block_data(slave_addr, MEMORY_ADDR,
                                              BYTE_LEN)
        # response = I2Cbus.read_byte_data(slave_addr, MEMORY_ADDR)
        I2Cbus.close()
        return "ok", int(bytearray(response).decode("utf-8", "ignore"))
        # return "ok", response
    except:
        I2Cbus.close()
        print("failed to retrieve data from arduino...")
        print(traceback.format_exc())
        return "error", traceback.format_exc()
示例#23
0
class Device(object):
    """Class for communicating with an I2C device using the adafruit-pureio pure
    python smbus library, or other smbus compatible I2C interface. Allows reading
    and writing 8-bit, 16-bit, and byte array values to registers
    on the device."""
    def __init__(self, address, busnum):
        """Create an instance of the I2C device at the specified address on the
        specified I2C bus number."""
        self._address = address
        self._bus = SMBus(busnum)
        self._logger = logging.getLogger('Rover_log')

    def writeByte(self, value):
        """Write an 8-bit value"""
        value = value & 0xFF
        self._bus.write_byte(self._address, register, value)
        self._logger.debug("Wrote 0x%02X to register 0x%02X", value, register)

    def write8(self, value, register=0):
        """Write an 8-bit value to the specified register. use register 0 if not needed"""
        value = value & 0xFF
        self._bus.write_byte_data(self._address, register, value)
        self._logger.debug("Wrote 0x%02X to register 0x%02X", value, register)

    def readU8(self, register=0):
        """Read an unsigned byte from the specified register. use 0 if egister is not needed"""
        result = self._bus.read_byte_data(self._address, register) & 0xFF
        self._logger.debug("Read 0x%02X from register 0x%02X", result,
                           register)
        return result

    def writeList(self, data, register=0):
        """Write bytes to the specified register. Use 0 if register is not needed"""
        self._bus.write_i2c_block_data(self._address, register, data)
        self._logger.debug("Wrote to register 0x%02X: %s", register, data)

    def readList(self, length, register=0):
        """Read a length number of bytes from the specified register, use 0 if register is not needed.  Results
        will be returned as a bytearray."""
        results = self._bus.read_i2c_block_data(self._address, register,
                                                length)
        self._logger.debug("Read the following from register 0x%02X: %s",
                           register, results)
        return results
示例#24
0
class LSM6:
    """
    Usage is:
            with LSM6() as imu:
    """
    DS33_SA0_HIGH_ADDRESS = 0b1101011
    DS33_SA0_LOW_ADDRESS = 0b1101010

    def __init__(self):
        self.bus = SMBus(1)
        self.address = self.DS33_SA0_HIGH_ADDRESS  # TODO: high address is assumed, SA0 connected to supply voltage
        # Enable Accelerometer high performance mode, ODR = 1000, (+-2g)
        self.bus.write_byte_data(self.address, RegAddr['CTRL1_XL'], 0x80)
        # Enable Gyro high performance mode, ODR = 1000, (245 dps)
        self.bus.write_byte_data(self.address, RegAddr['CTRL2_G'], 0x80)
        # Enable auto increment
        self.bus.write_byte_data(self.address, RegAddr['CTRL3_C'], 0x04)

    def read_values(self):
        """
        This function reads the IMUs measurements

        Returns:
            The sensors measurements in the following format
            (Gyro X, Gyro Y, Gyro Z, Acceleration X, Acc Y, Acc Z)
        """
        value_list = self.bus.read_i2c_block_data(
            self.address, RegAddr['OUTX_L_G'],
            RegAddr['OUTZ_H_XL'] - RegAddr['OUTX_L_G'])
        value_list = [(value_list[i], value_list[i + 1])
                      for i in range(0, len(value_list), 2)]
        value_list = list(map(_calc_value, value_list))
        for i in range(3):
            value_list[i] *= 4.375  # convert to MilliG
        for i in range(3, 6):
            value_list[i] *= 0.61  # convert to MilliDPS
        return tuple(value_list)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, exc_traceback):
        self.bus.close()
        return True
def main():

    # Initialize I2C (SMBus)
    bus = SMBus(1)
    arduino_addr = 0x7f

    arduino_status = [-1 for i in range(10)]

    while arduino_status[9] < 255:

        try:
            print("Requesting status: ", end='')
            arduino_status = bus.read_i2c_block_data(arduino_addr, 0, 10)
            #print(type(bus.read_byte(arduino_addr)))
        except OSError:
            print("OSError: Failed to read from specified peripheral")

        print("status:", arduino_status)
        sleep(10 // 1000)  # Take a picture
示例#26
0
class MPU6050:
    def __init__(self,):
        self.bus = SMBus(1)
        self.address = 0x68
        self.bus.write_byte_data(self.address, 0x6b, 0)
        self.bus.write_byte_data(self.address, 26, 3)

    def read_data(self,):
        raw_data = self.bus.read_i2c_block_data(self.address, 0x3B, 14)
        acc_x = (raw_data[0] << 8) + raw_data[1]

        if acc_x >= 0x8000:
            acc_x = -((65535 - acc_x) + 1)
        acc_x = acc_x / 16384.0
        acc_y = (raw_data[2] << 8) + raw_data[3]

        if acc_y >= 0x8000:
            acc_y = -((65535 - acc_y) + 1)
        acc_y = acc_y / 16384.0
        acc_z = (raw_data[4] << 8) + raw_data[5]

        if acc_z >= 0x8000:
            acc_z = -((65535 - acc_z) + 1)

        acc_z = acc_z / 16384.0
        z2 = acc_z * acc_z
        x_rot = math.degrees(math.atan2(acc_y, math.sqrt((acc_x * acc_x) + z2)))
        y_rot = -math.degrees(math.atan2(acc_x, math.sqrt((acc_y * acc_y) + z2)))
        gyro_x = (raw_data[8] << 8) + raw_data[9]

        if gyro_x >= 0x8000:
            gyro_x = -((65535 - gyro_x) + 1)

        gyro_x = gyro_x / 131.0
        gyro_y = (raw_data[10] << 8) + raw_data[11]

        if gyro_y >= 0x8000:
            gyro_y = -((65535 - gyro_y) + 1)
        gyro_y = gyro_y / 131.0

        return -x_rot, y_rot, acc_z, -gyro_x, gyro_y
示例#27
0
class JMOAB_ADC:
    def __init__(self):
        rospy.init_node('jmoab_ros_adc_node', anonymous=True)
        rospy.loginfo("Start JMOAB-ROS-ADC node")

        self.bus = SMBus(1)

        self.adc_pub = rospy.Publisher("/jmoab_adc",
                                       Float32MultiArray,
                                       queue_size=10)
        self.adc_array = Float32MultiArray()

        rospy.loginfo("Publishing ADC values on /jmoab_adc topic")

        self.loop()

        rospy.spin()

    def map(self, val, in_min, in_max, out_min, out_max):
        m = (out_max - out_min) / (in_max - in_min)
        out = m * (val - in_min) + out_min

        return out

    def convert2voltage(self, raw_list):

        raw_list = np.asarray(raw_list)
        voltage_array = self.map(raw_list, 0.0, 255.0, 0.0, 40.96)
        return voltage_array

    def loop(self):
        rate = rospy.Rate(10)
        while not rospy.is_shutdown():

            raw = self.bus.read_i2c_block_data(0x71, 0x00, 6)
            voltage_list = self.convert2voltage(raw)
            self.adc_array.data = voltage_list
            self.adc_pub.publish(self.adc_array)

            rate.sleep()
示例#28
0
class GDK101(object):
    '''driver code for GDK101 gamma ray sensor'''
    def __init__(self, busnum, addr):
        self.bus = SMBus(busnum)
        self.addr = addr
        rc = self.reset()
        if rc != 1:  # reset failed
            raise Exception('GKD101: failed to reset sensor')

    def _readGKD101(self, cmd):
        '''implement simple I²C interface of GDK101
       - send command
       - block-read two bytes
    '''
        self.bus.write_byte_data(self.addr, 0, cmd)
        return self.bus.read_i2c_block_data(self.addr, 0, 2)

    def reset(self):
        d = self._readGKD101(CMD_reset)
        return d[0]

    def read1(self):
        ''' read 1 min average'''
        d = self._readGKD101(CMD_readDose1)
        return d[0] + d[1] / 100.

    def read10(self):
        ''' read 10 min sliding average'''
        d = self._readGKD101(CMD_readDose10)
        return d[0] + d[1] / 100.

    def version(self):
        '''return firmware version'''
        fw = self._readGKD101(CMD_firmware)
        return str(fw[0] + fw[1] / 10.)

    def close(self):
        '''close bus'''
        self.bus.close()
示例#29
0
class I2C(object):
    def __init__(self, bus_number, device_address):
        self.smbus = SMBus(bus_number)
        self.device_address =  device_address


    def set_bit(self,register, index):
        read_value = np.uint8(self.smbus.read_byte_data(self.device_address, register))
        bit_array = np.unpackbits(read_value)
        bit_array[index*-1-1] = 1
        self.smbus.write_byte_data(self.device_address,register, np.packbits(bit_array))


    def clear_bit(self,register, index):
        read_value = np.uint8(self.smbus.read_byte_data(self.device_address, register))
        bit_array = np.unpackbits(read_value)
        bit_array[index*-1-1] = 0
        self.smbus.write_byte_data(self.device_address,register, np.packbits(bit_array))


    def read_bit(self,register, index):
        value = self.smbus.read_byte_data(device_address, register)
        eight_bit = format(value, '08b')
        return eight_bit[index*(-1)-1]


    def write_byte(self,register, value):
        self.smbus.write_byte_data(self.device_address,register, int(value))


    def read_byte(self, register):
        return self.smbus.read_byte_data(self.device_address,register)


    def read_block(self,register, number_to_read):
        return self.smbus.read_i2c_block_data(self.device_address, register, number_to_read)

    def byte_array_to_float32(self,array):
        return np.fromiter(array[::-1], dtype=np.uint8).view('<f4')
class I2C:
    """ Represents the I2C connection and all its
    functions necessary to create the communication
    between the Arduino and the Raspberry Pi. """
    def __init__(self, address, number_of_ldrs=2):
        self.connector = SMBus(1)
        self.SLAVE_ADDRESS = address
        self.number_of_ldrs = number_of_ldrs

    def get_arduino_data(self):
        """ Fetchs the Arduino data transfered through I2C. """
        return self.connector.read_i2c_block_data(self.SLAVE_ADDRESS, 1,
                                                  (self.number_of_ldrs * 2))

    def get_ldr_values(self):
        """ Gets the ldr values and validates it. """
        brute_data = self.get_arduino_data()
        ldr_values = convert_byte_to_integer(brute_data)
        if not is_valid_ldr_list(ldr_values):
            raise InvalidLDRListException
        if not is_valid_ldr_data(ldr_values):
            raise InvalidLDRListValuesException
        return ldr_values
示例#31
0
class InputModule(AbstractInput):
    """ A sensor support class that monitors the MH-Z16's CO2 concentration """

    def __init__(self, input_dev, testing=False):
        super(InputModule, self).__init__()
        self.logger = logging.getLogger("mycodo.inputs.mh_z16")

        if not testing:
            self.logger = logging.getLogger(
                "mycodo.mh_z16_{id}".format(id=input_dev.unique_id.split('-')[0]))

            self.interface = input_dev.interface
            self.uart_location = input_dev.uart_location

            if self.interface == 'UART':
                import serial

                # Check if device is valid
                self.serial_device = is_device(self.uart_location)
                if self.serial_device:
                    try:
                        self.ser = serial.Serial(self.serial_device, timeout=1)
                    except serial.SerialException:
                        self.logger.exception('Opening serial')
                else:
                    self.logger.error(
                        'Could not open "{dev}". '
                        'Check the device location is correct.'.format(
                            dev=self.uart_location))

            elif self.interface == 'I2C':
                from smbus2 import SMBus

                self.i2c_address = int(str(input_dev.i2c_location), 16)
                self.i2c_bus = input_dev.i2c_bus
                self.cmd_measure = [0xFF, 0x01, 0x9C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63]
                self.IOCONTROL = 0X0E << 3
                self.FCR = 0X02 << 3
                self.LCR = 0X03 << 3
                self.DLL = 0x00 << 3
                self.DLH = 0X01 << 3
                self.THR = 0X00 << 3
                self.RHR = 0x00 << 3
                self.TXLVL = 0X08 << 3
                self.RXLVL = 0X09 << 3
                self.i2c = SMBus(self.i2c_bus)
                self.begin()

    def get_measurement(self):
        """ Gets the MH-Z16's CO2 concentration in ppmv via UART"""
        return_dict = measurements_dict.copy()

        co2 = None

        if self.interface == 'UART':
            if not self.serial_device:  # Don't measure if device isn't validated
                return None

            self.ser.flushInput()
            time.sleep(1)
            self.ser.write(bytearray([0xff, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79]))
            time.sleep(.01)
            resp = self.ser.read(9)
            if len(resp) != 0:
                high = resp[2]
                low = resp[3]
                co2 = (high * 256) + low

        elif self.interface == 'I2C':
            self.write_register(self.FCR, 0x07)
            self.send(self.cmd_measure)
            try:
                co2 = self.parse(self.receive())
            except Exception:
                co2 = None

        return_dict[0]['value'] = co2

        return return_dict

    def begin(self):
        try:
            self.write_register(self.IOCONTROL, 0x08)
        except IOError:
            pass

        self.write_register(self.FCR, 0x07)
        self.write_register(self.LCR, 0x83)
        self.write_register(self.DLL, 0x60)
        self.write_register(self.DLH, 0x00)
        self.write_register(self.LCR, 0x03)

    @staticmethod
    def parse(response):
        checksum = 0

        if len(response) < 9:
            return None

        for i in range(0, 9):
            checksum += response[i]

        if response[0] == 0xFF:
            if response[1] == 0x9C:
                if checksum % 256 == 0xFF:
                    return (response[2] << 24) + (response[3] << 16) + (response[4] << 8) + response[5]

        return None

    def read_register(self, reg_addr):
        time.sleep(0.01)
        return self.i2c.read_byte_data(self.i2c_address, reg_addr)

    def write_register(self, reg_addr, val):
        time.sleep(0.01)
        self.i2c.write_byte_data(self.i2c_address, reg_addr, val)

    def send(self, command):
        if self.read_register(self.TXLVL) >= len(command):
            self.i2c.write_i2c_block_data(self.i2c_address, self.THR, command)

    def receive(self):
        n = 9
        buf = []
        start = time.clock()

        while n > 0:
            rx_level = self.read_register(self.RXLVL)

            if rx_level > n:
                rx_level = n

            buf.extend(self.i2c.read_i2c_block_data(self.i2c_address, self.RHR, rx_level))
            n = n - rx_level

            if time.clock() - start > 0.2:
                break
        return buf
示例#32
0
文件: am2320.py 项目: Routout/Mycodo
class InputModule(AbstractInput):
    """
    A sensor support class that measures the AM2320's humidity and temperature
    and calculates the dew point

    """
    def __init__(self, input_dev, testing=False):
        super(InputModule, self).__init__()
        self.setup_logger(testing=testing, name=__name__, input_dev=input_dev)
        self.powered = False
        self.sensor = None
        self.i2c_address = 0x5C

        if not testing:
            from smbus2 import SMBus

            self.device_measurements = db_retrieve_table_daemon(
                DeviceMeasurements).filter(
                    DeviceMeasurements.device_id == input_dev.unique_id)

            self.i2c_bus = input_dev.i2c_bus
            self.power_output_id = input_dev.power_output_id
            self.start_sensor()
            self.sensor = SMBus(self.i2c_bus)

    def get_measurement(self):
        """ Gets the humidity and temperature """
        self.return_dict = measurements_dict.copy()

        temperature, humidity = self.read()

        if self.is_enabled(0):
            self.set_value(0, temperature)

        if self.is_enabled(1):
            self.set_value(1, humidity)

        if (self.is_enabled(2) and self.is_enabled(0) and self.is_enabled(1)):
            self.set_value(
                2, calculate_dewpoint(self.get_value(0), self.get_value(1)))

        if (self.is_enabled(3) and self.is_enabled(0) and self.is_enabled(1)):
            self.set_value(
                3,
                calculate_vapor_pressure_deficit(self.get_value(0),
                                                 self.get_value(1)))

        return self.return_dict

    def read(self):
        try:
            self.sensor.write_i2c_block_data(self.i2c_address, 0x03,
                                             [0x00, 0x04])
        except OSError as e:
            self.logger.error(e)
        time.sleep(0.02)

        blocks = self.sensor.read_i2c_block_data(self.i2c_address, 0, 6)

        humidity = ((blocks[2] << 8) + blocks[3]) / 10.0
        temperature = ((blocks[4] << 8) + blocks[5]) / 10.0

        return temperature, humidity

    def setup(self):
        try:
            self.sensor.write_i2c_block_data(self.i2c_address, 0x00, [])
        except OSError as e:
            self.logger.error(e)
        time.sleep(0.1)
示例#33
0
class InputModule(AbstractInput):
    """
    A sensor support class that measures the AM2320's humidity and temperature
    and calculates the dew point

    """
    def __init__(self, input_dev, testing=False):
        super(InputModule, self).__init__()
        self.logger = logging.getLogger('mycodo.inputs.am2320')
        self.powered = False
        self.sensor = None
        self.i2c_address = 0x5C

        if not testing:
            from smbus2 import SMBus
            self.logger = logging.getLogger(
                'mycodo.am2320_{id}'.format(
                    id=input_dev.unique_id.split('-')[0]))

            self.device_measurements = db_retrieve_table_daemon(
                DeviceMeasurements).filter(
                    DeviceMeasurements.device_id == input_dev.unique_id)

            self.i2c_bus = input_dev.i2c_bus
            self.power_output_id = input_dev.power_output_id
            self.start_sensor()
            self.sensor = SMBus(self.i2c_bus)

    def get_measurement(self):
        """ Gets the humidity and temperature """
        return_dict = measurements_dict.copy()

        temperature, humidity = self.read()

        if self.is_enabled(0):
            return_dict[0]['value'] = temperature

        if self.is_enabled(1):
            return_dict[1]['value'] = humidity

        if (self.is_enabled(2) and
                self.is_enabled(0) and
                self.is_enabled(1)):
            return_dict[2]['value'] = calculate_dewpoint(
                return_dict[0]['value'], return_dict[1]['value'])

        if (self.is_enabled(3) and
                self.is_enabled(0) and
                self.is_enabled(1)):
            return_dict[3]['value'] = calculate_vapor_pressure_deficit(
                return_dict[0]['value'], return_dict[1]['value'])

        return return_dict

    def read(self):
        try:
            self.sensor.write_i2c_block_data(
                self.i2c_address, 0x03, [0x00, 0x04])
        except OSError as e:
            self.logger.error(e)
        time.sleep(0.02)

        blocks = self.sensor.read_i2c_block_data(self.i2c_address, 0, 6)

        humidity = ((blocks[2] << 8) + blocks[3]) / 10.0
        temperature = ((blocks[4] << 8) + blocks[5]) / 10.0

        return temperature, humidity

    def setup(self):
        try:
            self.sensor.write_i2c_block_data(self.i2c_address, 0x00, [])
        except OSError as e:
            self.logger.error(e)
        time.sleep(0.1)