示例#1
0
 def __init__(self):
     threading.Thread.__init__(self)
     self.ADDRESS_DEVICE = 0x5A
     self.ADDRESS_OBJECT1 = 0x07
     self.sensor = I2C.Device(self.ADDRESS_DEVICE, 1)
     self.corriendo = True
     self.temperturaOrgano = None
示例#2
0
    def __init__(self, address=__INA219_ADDRESS, debug=False):
        #		self.i2c = Adafruit_I2C(address, debug=False)
        self.i2c = I2C.Device(address, 1)
        self.address = address
        self.debug = debug

        self.ina219SetCalibration_32V_2A()
示例#3
0
   def __init__(self, address=0x18, bus=1, debug=False):
      self.isDebug = debug
      self.debug("Initialising LIS3DH")

      self.i2c = I2C.Device(address, busnum=bus)
      self.address = address

      try:
         val = self.i2c.readU8(self.REG_WHOAMI)
         if val!=self.DEVICE_ID:
            raise Exception("Device ID incorrect - expected 0x%X, got 0x%X at address 0x%X" % (self.DEVICE_ID, val, self.address))
         self.debug("Successfully connected to LIS3DH at address 0x%X" % (self.address))
      except Exception as e:
         print "Error establishing connection with LIS3DH"
         print e

      # Enable all axis
      self.setAxisStatus(self.AXIS_X, True)
      self.setAxisStatus(self.AXIS_Y, True)
      self.setAxisStatus(self.AXIS_Z, True)

      # Set 400Hz refresh rate
      self.setDataRate(self.DATARATE_400HZ)

      self.setHighResolution()
      self.setBDU()

      self.setRange(self.RANGE_16G)
 def begin(self, addr=0x70, bus=-1):
     """Initialize the Trellis at the provided I2C address and bus number."""
     self._i2c = I2C.Device(addr, bus)
     self._i2c.writeList(0x21, [])  # Turn on the oscillator.
     self.blinkRate(HT16K33_BLINK_OFF)
     self.setBrightness(15)  # Max brightness.
     self._i2c.writeList(0xA1, [])  # Turn on interrupt, active high.
示例#5
0
    def __init__(self, address):
        #Setup the I2C component
        self.i2c = I2C.Device(0x76, 2)
        #Verify the ID
        if (self.ID() != 0x60):
            print "ERROR!  Got an invalid ID: " + hex(self.ID())

        #Perform a soft reset
        self.SoftReset()
        #set data acquisition options
        self.i2c.write8(self.CTRL_HUMIDITY_REG,
                        0x01)  #x1 humidity oversampling
        self.i2c.write8(
            self.CTRL_MEAS_REG,
            0xAB)  # 10101011 - 16x pressure, 2x temperature, normal mode
        self.i2c.write8(self.CONFIG_REG,
                        0x08)  # 0001000 - filter 16, t_standby 0.5ms
        #Read in calibration data
        print "Initialization complete.  Waiting for first valid measurement."
        time.sleep(0.007125)  #sleep 7.125ms for acquisition
        self.GetCalibrationValues()
        [p, t, h] = self.GetUncompensatedValues()
        while p == t:
            time.sleep(0.5)
            [p, t, h] = self.GetUncompensatedValues()
        print "Sensor ready."
示例#6
0
def htu21df_read():
    # https://www.adafruit.com/product/1899
    # https://github.com/adafruit/Adafruit_HTU21DF_Library/
    # https://github.com/dalexgray/RaspberryPI_HTU21DF/

    import Adafruit_GPIO.I2C as I2C

    temp_read = 0xE3
    hum_read = 0xE5
    write_reg = 0xE6
    soft_reset = 0xFE

    htu_addy = 0x40
    bus = 0

    array = [0x00, 0x00]

    dev0 = I2C.Device(htu_addy, bus)
    dev0.write8(soft_reset,
                write_reg)  # does this actually reset it? prly not....
    time.sleep(0.2)

    array = dev0.readList(temp_read, 2)
    t0 = (array[0] * 256.0) + array[1]
    temp = ((t0 * 175.72) / 65536) - 46.85

    array = dev0.readList(hum_read, 2)
    h0 = (array[0] * 256.0) + array[1]
    hum = ((h0 * 125) / 65536) - 6

    return (temp, hum)
示例#7
0
    def ad9577_init(self):
        self.i2c = I2C.Device(AD9577_I2C_ADDR, 1)
        self.i2c.write8(0x40, 0x02)  # enable i2c, set EnI2C on register C0

        self.i2c.write8(
            0x3A, 0x0f
        )  # enable CH2 and CH3, LVDS on CH2 and CH3, CMOS for CH0 and CH1 on register DR1
        self.i2c.write8(0x3B, 0x00)  # enable refout, set PDRefOut on DR2 to 0

        self.i2c.write8(0x11, 0x03)  # power down CH0 and CH1

        # fpfd = 26 MHz
        # fout = fpfd * n / (v * d)
        # vco from 2.15 GHz to 2.55 GHz
        # n is 80 to 131
        # v from 2 to 6
        # d from 1 to 31

        # configure ppl1 (int mode)
        self.i2c.write8(0x18,
                        0x0a)  # set n to 90 in register AF0 (vco of 2340 MHz)
        self.i2c.write8(0x22, 0x8d)  # set v0 to 4, d0 to 13 on register ADV0
        self.i2c.write8(0x23, 0x8d)  # set v1 to 4, d1 to 13 on register ADV1

        # configure pll2 (int mode)
        self.i2c.write8(0x1C,
                        0x05)  # set n to 85 in register BF3 (vco of 2210 MHz)
        self.i2c.write8(0x25, 0x4d)  # set v2 to 2, d2 to 13 on register BDV0
        self.i2c.write8(0x26, 0x4d)  # set v2 to 2, d2 to 13 on register BDV1

        # finish configuration

        self.i2c.write8(0x1F, 0x00)
        self.i2c.write8(0x1F, 0x01)  # force new acquisition by toggling NewAcq
        self.i2c.write8(0x1F, 0x00)
示例#8
0
    def __init__(self, address=0x18, bus=-1):
        log.debug("Initialising LIS3DH")

        self.i2c = I2C.Device(address, busnum=bus)
        self.address = address

        try:
            val = self.i2c.readU8(self.REG_WHOAMI)
            if val != self.DEVICE_ID:
                raise Exception(
                    "Device ID incorrect - expected 0x%X, got 0x%X at address 0x%X"
                    % (self.DEVICE_ID, val, self.address))
            log.debug("Successfully connected to LIS3DH at address 0x%X" %
                      self.address)
        except Exception:
            raise Exception("Error establishing connection with LIS3DH")

        # Enable all axis
        self.set_axis_status(self.AXIS_X, True)
        self.set_axis_status(self.AXIS_Y, True)
        self.set_axis_status(self.AXIS_Z, True)

        # Set 400Hz refresh rate
        self.set_data_rate(self.DATARATE_400HZ)
        self.set_high_resolution()
        self.set_bdu()
        self.set_range(self.RANGE_2G)
示例#9
0
    def __init__(self, address=I2C_DEFAULT, bus=BUS_NUMBER,
                 g_range=RANGE_DEFAULT, datarate=DATARATE_DEFAULT,
                 debug=False):
        self.isDebug = debug
        self.debug("Initialising LIS3DH")

        # self.i2c = Adafruit_I2C(address, busnum=bus)
        self.i2c = I2C.Device(address, busnum=bus)
        self.address = address

        try:
            val = self.i2c.readU8(self.REG_WHOAMI)
            if val != self.DEVICE_ID:
                raise Exception(("Device ID incorrect - expected 0x{:x}, " +
                                 "got 0x{:x} at address 0x{:x}").format(self.DEVICE_ID, val, self.address))

            self.debug(("Successfully connected to LIS3DH " +
                        "at address 0x{:x}").format(self.address))
        except Exception as e:
            print("Error establishing connection with LIS3DH")
            print(e)

        # Enable all axis
        self.setAxisStatus(self.AXIS_X, True)
        self.setAxisStatus(self.AXIS_Y, True)
        self.setAxisStatus(self.AXIS_Z, True)

        # Set refresh rate (default: 400Hz)
        self.setDataRate(datarate)

        self.setHighResolution()
        self.setBDU()

        self.setRange(g_range)
示例#10
0
 def __init__(self, deviceAddr, busNum, interface, bitSize):
     """
         this class initiate and inject the value into the class,implementing 
         dependency injection pattern
     """
     self.sensorConfig["interface"] = interface
     self.sensorConfig["bitSize"] = bitSize
     self.sensorConfig["i2c"] = I2C.Device(deviceAddr, busNum)
示例#11
0
 def setup_i2c(self):
     if not self.device_on:
         try:
             self._i2c = I2C.Device(TEPERATURE_ADDRESS, busnum=1)
             self.device_on = True
         except:
             logging.error('[Temperature sensor] cannot start device')
             self.device_on = False
示例#12
0
 def __init__(self):
     #step 1: set cmd for both accel and gyro
     self.Device = I2C.Device(address=0x69,
                              busnum=2)  #i2c address and busNum in BB
     #self.Device.writeList(0x7E,bytearray(b'\x11\x15\x18'))
     self.Device.write8(0x7E, 0x11)  #write to gyro
     self.Device.write8(0x7E, 0x15)  #write to accel
     self.Device.write8(0x7E, 0x18)  #write to accel
     time.sleep(0.1)  #sensor need time of 100ms to set
def create_device(address, busnum):
    # Mock the smbus module and inject it into the global namespace so the
    # Adafruit_GPIO.I2C module can be imported.  Also inject a mock SMBus
    # instance to be returned by smbus.SMBus function calls.
    smbus = Mock()
    mockbus = MockSMBus()
    smbus.SMBus.return_value = mockbus
    with patch.dict('sys.modules', {'smbus': smbus}):
        import Adafruit_GPIO.I2C as I2C
        return (I2C.Device(address, busnum), smbus, mockbus)
示例#14
0
 def __init__(self, deviceAddr=0x47, busNum=2, interface=None, bitSize=10):
     super().__init__(deviceAddr, busNum, interface, bitSize)
     self.device = I2C.Device(address=0x47, busnum=2)
     self.device.writeList(
         0x01, bytearray(b'\xc4\x10')
     )  #configure the mode (refer to datasheet configuration table)
     #0x01 - config adr
     #0xc4 - full scale, 100ms conv. time, contiue measuring
     #0x10 - latch
     time.sleep(0.1)  #wait for 100ml for the sensor to take place
示例#15
0
 def __init__(self, address=0x48, mode=1, debug=False):
     self.i2c = I2C.Device(address, busnum=1)
     self.address = address
     self.debug = debug
     # Make sure the specified mode is in the appropriate range
     if ((mode < 0) | (mode > 3)):
         if (self.debug):
             print "Invalid Mode: Using STANDARD by default"
         self.mode = self.__BMP085_STANDARD
     else:
         self.mode = mode
示例#16
0
	def __init__(self, mode=BMP085_STANDARD, address=BMP085_I2CADDR, 
							 busnum=I2C.get_default_bus()):
		self._logger = logging.getLogger('Adafruit_BMP.BMP085')
		# Check that mode is valid.
		if mode not in [BMP085_ULTRALOWPOWER, BMP085_STANDARD, BMP085_HIGHRES, BMP085_ULTRAHIGHRES]:
			raise ValueError('Unexpected mode value {0}.  Set mode to one of BMP085_ULTRALOWPOWER, BMP085_STANDARD, BMP085_HIGHRES, or BMP085_ULTRAHIGHRES'.format(mode))
		self._mode = mode
		# Create I2C device.
		self._device = I2C.Device(address, busnum)
		# Load calibration values.
		self._load_calibration()
示例#17
0
    def __init__(self, address=SI1145_ADDR, busnum=I2C.get_default_bus()):

        self._logger = logging.getLogger('SI1145')

        # Create I2C device.
        self._device = I2C.Device(address, busnum)

        # reset device
        self._reset()

        # Load calibration values.
        self._load_calibration()
示例#18
0
        def __init__(self, mode=TMP007_CFG_16SAMPLE, address=TMP007_I2CADDR,
                                                         busnum=I2C.get_default_bus()):

                self._logger = logging.getLogger('TMP007')

                # Check that mode is valid.
                if mode not in [TMP007_CFG_1SAMPLE, TMP007_CFG_2SAMPLE, TMP007_CFG_4SAMPLE, TMP007_CFG_8SAMPLE, TMP007_CFG_16SAMPLE]:
                        raise ValueError('Unexpected mode value {0}.  Set mode to one of TMP007_CFG_1SAMPLE, TMP007_CFG_2SAMPLE, TMP007_CFG_4SAMPLE, TMP007_CFG_8SAMPLE or TMP007_CFG_16SAMPLE'.format(mode))
                self._mode = mode
                # Create I2C device.
                self._device = I2C.Device(address, busnum)
                # Load calibration values.
                self._load_calibration()
 def __init__(self, addr=0x39, debug=False):
     self._debug = debug
     if (self._debug == True): print "__init__"
     self._addr = addr
     self._tsl2561Initialised = False
     self._tsl2561AutoGain = False
     self._tsl2561IntegrationTime = self.TSL2561_INTEGRATIONTIME_13MS
     self._tsl2561Gain = self.TSL2561_GAIN_1X
     self._i2c = I2C.Device(self._addr, 1)
     self._luminosity = 0
     self._broadband = 0
     self._ir = 0
     if (self._debug == True): print "__init___end"
示例#20
0
    def __init__(self, address, busnum=I2C.get_default_bus()):
        """Initialize MCP230xx at specified I2C address and bus number.  If bus
		is not specified it will default to the appropriate platform detected bus.
		"""
        self._i2c = I2C.Device(address, busnum)
        # Assume starting in ICON.BANK = 0 mode (sequential access).
        # Compute how many bytes are needed to store count of GPIO.
        self.gpio_bytes = int(math.ceil(self.NUM_GPIO / 8.0))
        # Buffer register values so they can be changed without reading.
        self.iodir = [0x00
                      ] * self.gpio_bytes  # Default direction to all inputs.
        self.gppu = [0x00] * self.gpio_bytes  # Default to pullups disabled.
        self.gpio = [0x00] * self.gpio_bytes
        # Write current direction and pullup buffer state.
        self.write_iodir()
        self.write_gppu()
示例#21
0
        def __init__(self, address=SI1145_ADDR, busnum=I2C.get_default_bus()):
                try:
                        self._logger = logging.getLogger('SI1145')

                        # Create I2C device.
                        self._device = I2C.Device(address, busnum)

                        #reset device
                        self._reset()

                        # Load calibration values.
                        self._load_calibration()

                        isFound = True
                except:
                        logging.info("si1145 not found.")
示例#22
0
    def __init__(self, address=LTC2946_I2CADDR, i2c=None):
        # Create I2C device.
        if i2c is None:
            raise ValueError('Error I2C object is required.')
        # Create device, catch permission errors

        self.i2c = i2c
        self.address = address
        result = self.address in self.i2c.scan()
        if result is False:
            print("Unable to communicate with sensor, check connections.")
            exit()

        import Adafruit_GPIO.I2C as I2C

        self._device = I2C.Device(address, i2c)
示例#23
0
        def __init__(self, address=SI1145_ADDR, busnum=I2C.get_default_bus()):
                ''' (default [I2C address of SI1145=0x60], [I2C bus number])
                intitalizes to default mode (UV,Vis,IR and Prox 1)
                enables all interupts and starts in autonomous mode'''

                self._logger = logging.getLogger('SI1145')

                # Create I2C device.
                self._device = I2C.Device(address, busnum)

                #reset device
                self._reset()

                # Load calibration values, default settings, enables interupts
                # and starts in autonomous mode.
                self._load_setup()
示例#24
0
    def __init__(self, mode=BMP085_STANDARD, address=BMP085_I2CADDR, 
                             busnum=I2C.get_default_bus()):
        self._logger = logging.getLogger('Adafruit_BMP.BMP085')
        # Check that mode is valid.
        if mode not in [BMP085_ULTRALOWPOWER, BMP085_STANDARD, BMP085_HIGHRES, BMP085_ULTRAHIGHRES]:
            raise ValueError('Unexpected mode value {0}.  Set mode to one of BMP085_ULTRALOWPOWER, BMP085_STANDARD, BMP085_HIGHRES, or BMP085_ULTRAHIGHRES'.format(mode))
        self._mode = mode
        # Create I2C device.
        self._device = I2C.Device(address, busnum)
        #(chip_id, version) = bus.read_i2c_block_data(addr, 0xD0, 2)
        chip_id = self._device.readU8(0xD0)
        version = self._device.readU8(0xD0 + 1)
        self._logger.debug('Chip Id: {0} Version: {1}'.format(chip_id, version))
        # Load calibration values.
        self._load_calibration()
        self._compute_polynomials()

        self.temperature=None
 def __init__(self,
              width,
              height,
              rst,
              dc=None,
              sclk=None,
              din=None,
              cs=None,
              gpio=None,
              spi=None,
              i2c_bus=I2C.get_default_bus(),
              i2c_address=SSD1306_I2C_ADDRESS):
     self._log = logging.getLogger('Adafruit_SSD1306.SSD1306Base')
     self._spi = None
     self._i2c = None
     self.width = width
     self.height = height
     self._pages = height / 8
     self._buffer = [0] * (width * self._pages)
     # Default to platform GPIO if not provided.
     self._gpio = gpio if gpio is not None else GPIO.get_platform_gpio()
     # Setup reset pin.
     self._rst = rst
     self._gpio.setup(self._rst, GPIO.OUT)
     # Handle hardware SPI
     if spi is not None:
         self._log.debug('Using hardware SPI')
         self._spi = spi
     # Handle software SPI
     elif sclk is not None and din is not None and cs is not None:
         self._log.debug('Using software SPI')
         self._spi = SPI.BitBang(self._gpio, sclk, din, None, cs)
     # Handle hardware I2C
     elif i2c_bus is not None:
         self._log.debug('Using hardware I2C')
         self._i2c = I2C.Device(i2c_address, i2c_bus)
     else:
         raise ValueError('Unable to determine if using SPI or I2C.')
     # Initialize DC pin if using SPI.
     if self._spi is not None:
         if dc is None:
             raise ValueError('DC pin must be provided when using SPI.')
         self._dc = dc
         self._gpio.setup(self._dc, GPIO.OUT)
示例#26
0
 def __init__(self, address=_TSL2591_ADDR, i2c=None):
     self.i2c = i2c
     self.address = address
     self._integration_time = 0
     self._gain = 0
     self._device = I2C.Device(address,i2c)
     # Verify the chip ID.
     result = self.address in self.i2c.scan()
     if result is False:
         #raise RuntimeError('Failed to find TSL2591, check wiring!')
         print("Unable to communicate with sensor, check connections.")
         exit()
     #if self._device.readU8(_TSL2591_REGISTER_DEVICE_ID) != 0x50:
     #    raise RuntimeError('Failed to find TSL2591, check wiring!')
     # Set default gain and integration times.
     self.gain = GAIN_MED
     self.integration_time = INTEGRATIONTIME_100MS
     # Put the device in a powered on state after initialization.
     self.enable()
示例#27
0
def start_daq(time_step,num_sample):
	# create an instance of a sensor connected to i2c
	sensor = I2C.Device(MPUADDR, BUSNUM)
	# wake up the sensor
	sensor.write8(PWR_MGMT_1, 0)
	
	ax_list = []
	ay_list = []
	az_list = []
	dt_list = []

	for i in range(num_sample):
		ax_list.append(sensor.readS16(ACC_X, False) / ACC_SF)
		ay_list.append(sensor.readS16(ACC_Y, False) / ACC_SF)
		az_list.append(sensor.readS16(ACC_Z, False) / ACC_SF)
		dt_list.append(datetime.datetime.now())
		time.sleep(time_step)

	return dt_list,ax_list,ay_list,az_list
示例#28
0
    def __init__(self, address, num_gpios, busnum=-1):
        assert num_gpios >= 0 and num_gpios <= 16, "Number of GPIOs must be between 0 and 16"
        # busnum being negative will have Adafruit_I2C figure out what is appropriate for your Pi
        self.i2c = I2C.Device(address=address, busnum=busnum)
        self.address = address
        self.num_gpios = num_gpios

        # set defaults
        self.i2c.write8(MCP23017_IODIRA, 0xFF)  # all inputs on port A
        self.i2c.write8(MCP23017_IODIRB, 0xFF)  # all inputs on port B

        # read the current direction of all pins into instance variable
        # self.direction used for assertions in a few methods methods
        self.direction = self.i2c.readU8(MCP23017_IODIRA)
        self.direction |= self.i2c.readU8(MCP23017_IODIRB) << 8

        # disable the pull-ups on all ports
        self.i2c.write8(MCP23017_GPPUA, 0x00)
        self.i2c.write8(MCP23017_GPPUB, 0x00)

        # clear the IOCON configuration register, which is chip default
        self.i2c.write8(MCP23017_IOCON, 0x00)

        ##### interrupt defaults
        # disable interrupts on all pins by default
        self.i2c.write8(MCP23017_GPINTENA, 0x00)
        self.i2c.write8(MCP23017_GPINTENB, 0x00)
        # interrupt on change register set to compare to previous value by default
        self.i2c.write8(MCP23017_INTCONA, 0x00)
        self.i2c.write8(MCP23017_INTCONB, 0x00)
        # interrupt compare value registers
        self.i2c.write8(MCP23017_DEFVALA, 0x00)
        self.i2c.write8(MCP23017_DEFVALB, 0x00)
        # clear any interrupts to start fresh
        self.i2c.readU8(MCP23017_GPIOA)
        self.i2c.readU8(MCP23017_GPIOB)
示例#29
0
'''
#   Debugging Options

verbose = False
log_output_location = "./scuttle_debugging.log"

#   ADC Settings

valid_adc_pins = ("AIN0", "AIN1", "AIN2", "AIN3")

#   IMU Settings

#   Compass Settings

comapss_i2c = Adafruit_I2C.Device(0x1e, 1)  # I2C Bus Device Location

compass_write_registers = (0x00, 0x02)  # Registers to Write Data to
compass_write_registers_data = (0x70, 0x01)  # Data to Write to Registers

#   Rotary Encoder Settings

right_encoder = Adafruit_I2C.Device(
    0x40, 1
)  # Power the Rotary Encoder Address Select Pin to change the address of the left encoder
left_encoder = Adafruit_I2C.Device(
    0x41, 1
)  # Power pin A0 to set address to 0x41 (default) or power pin A1 to set address to 0x42

#   Motor Controller Settings
示例#30
0
 def __init__(self, address=0x5A):
     self._i2c = I2C.Device(address, busnum=1)