示例#1
0
 def _print_all(self):
     for i in range(2):
         if self._board_status[i]:
             _print_gpio_registers(
                 I2C.get_i2c_device(self._gpio_addresses[i], self._bus))
             _print_pwm_registers(
                 I2C.get_i2c_device(self._pwm_addresses[i], self._bus))
def get_i2c_device(address, i2c, i2c_bus):
    """
	Helper method to get a device at the specified address from the I2C bus.
	If no i2c bus is specified (i2c param is None) then the default I2C bus
	for the platform will be used.

	:param address:
		i2c address to get the handle for
	:type address:
		hex
	:param i2c:
		GPIO i2c class, None to use the Adafruit_GPIO.I2C class
	:param i2c_bus:
		i2c bus number, passed to busnum, none to autodetect
	:return:
		i2c Address
	"""
    if i2c is not None:
        return i2c.get_i2c_device(address)
    else:
        import Adafruit_GPIO.I2C as I2C
        if i2c_bus is None:
            return I2C.get_i2c_device(address)
        else:
            return I2C.get_i2c_device(address, busnum=i2c_bus)
 def __init__(self,
              width,
              height,
              rst,
              gpio=1,
              i2c_bus=1,
              i2c_address=SSD1306_I2C_ADDRESS,
              i2c=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.
     # Platform identification constants.
     # UNKNOWN          = 0
     # RASPBERRY_PI     = 1
     self._gpio = gpio
     # Setup reset pin.
     self._rst = rst
     if not self._rst is None:
         self._gpio.setup(self._rst, GPIO.OUT)
     if i2c_bus is None:
         self._i2c = I2C.get_i2c_device(i2c_address)
     else:
         self._i2c = I2C.get_i2c_device(i2c_address, busnum=i2c_bus)
示例#4
0
    def __init__(self, busnum=None):
        # Each feature is given a call name. Although The magnetometer and
        # accelerometer use the same address, they've been given different
        # names for clarity.
        self.mag = I2C.get_i2c_device(self.LSM9DS0_MAG_ADDRESS, busnum)
        self.accel = I2C.get_i2c_device(self.LSM9DS0_ACCEL_ADDRESS, busnum)
        self.gyro = I2C.get_i2c_device(self.LSM9DS0_GYRO_ADDRESS, busnum)

        # Magnetometer initialisation
        self.mag.write8(
            self.LSM9DS0_CTRL_REG5_XM,
            0b11110000)  # Temperature sensor enabled, high res mag, 50Hz
        #Actually Chodge and I just disabled the temperature sensor... JK, it threw errors
        self.mag.write8(self.LSM9DS0_CTRL_REG6_XM, 0b01100000)  # +/- 12 gauss
        self.mag.write8(self.LSM9DS0_CTRL_REG7_XM,
                        0b00000000)  # Normal mode, continuous-conversion mode

        # Accelerometer initialisation
        self.accel.write8(self.LSM9DS0_CTRL_REG1_XM,
                          0b01100111)  # 100Hz, XYZ enabled
        self.accel.write8(self.LSM9DS0_CTRL_REG2_XM, 0b00000000)  # +/- 2 g
        #chodge and I made this the most sensitive it could be.

        # Gyro initialisation
        self.gyro.write8(self.LSM9DS0_CTRL_REG1_G,
                         0b00001111)  # Normal power mode, XYZ enabled
        self.gyro.write8(self.LSM9DS0_CTRL_REG4_G,
                         0b00000000)  # Continuous update, 245 dps
    def __init__(self, i2c_bus=None):
        self._key_hit = False
        self._hold_down = False
        self._init_ok = False
        Controller.available_pins = [self.TOUCH_RESET_PIN] + Controller.available_pins
        Controller.available_pins = [self.TOUCH_CHANGE_PIN] + Controller.available_pins
        self._reset_pin = Controller.alloc_pin(self.TOUCH_RESET_PIN, OUTPUT)
        self._reset_pin.set()
        self._change_pin = Controller.alloc_pin(self.TOUCH_CHANGE_PIN, INPUT, self._read_state, FALLING)
        time.sleep(1)

        if i2c_bus is None:
            self._i2c = I2C.get_i2c_device(self.TOUCH_I2C_ADDRESS)
        else:
            self._i2c = I2C.get_i2c_device(self.TOUCH_I2C_ADDRESS, busnum=i2c_bus)
        # write non-zero value to reset register
        time.sleep(0.5)
        self._i2c.write8(self.TOUCH_CMD_RESET, 0xff)
        time.sleep(0.5)
        chip_id = self._i2c.readU8(self.TOUCH_CMD_CHIP_ID)
        time.sleep(0.5)
        self._i2c.write8(self.TOUCH_CMD_CALIBRATE, 0xff)
        while self._i2c.readU8(self.TOUCH_CMD_DETECTION_STATUS) & 0x80:
            self.logger.debug("init: calibration in progress ...")
        self._i2c.write8(self.TOUCH_CMD_MAX_ON_DURATION, 100)
        if chip_id == self.TOUCH_CHIP_ID:
            self._init_ok = True
        self._i2c.write8(self.TOUCH_CMD_FAST_MAX_CAL_GUARD, 0x6)
        time.sleep(0.1)
        # increase sensitivity
        for i in range(0, 7):
            self._i2c.write8(self.TOUCH_CMD_NEGATIVE_TRESHOLD + i, 80)
            time.sleep(0.1)
示例#6
0
 def _check_active_addresses(self, i, bus):
     x, y = None, None
     try:
         self._gpio[i] = I2C.get_i2c_device(self._gpio_addresses[i], bus)
         self._pwm[i] = I2C.get_i2c_device(self._pwm_addresses[i], bus)
         x = self._gpio[i].readU8(0x00)
         y = self._pwm[i].readU8(0x00)
     except OSError:
         self._gpio[i] = None
         self._pwm[i] = None
         self._board_status[i] = 0
     finally:
         if x is not None and y is not None:
             self._board_status[i] = 1
             self._gpio[i].write8(0x03, 0xE0)
             self._gpio[i].write8(0x01, 0xE0)
             x = self._pwm[i].readU8(0x00)
             if x & 0x80 == 0x80:
                 self._pwm[i].write8(0x00, 0x80)
             self._pwm[i].write8(0x00, 0x30)
             prescaler = (round(25000000 /
                                (4096 * self._board_freq[i])) - 1) & 0xFF
             self._pwm[i].write8(0xFE, prescaler)
             self._pwm[i].write8(0x00, 0x20)
             for z in range(2, 6):
                 self._pwm[i].write8(z, 0x00)
示例#7
0
    def __init__(self,
                 width,
                 height,
                 rst,
                 dc=None,
                 sclk=None,
                 din=None,
                 cs=None,
                 gpio=None,
                 spi=None,
                 i2c_bus=None,
                 i2c_address=SSD1306_I2C_ADDRESS,
                 i2c=None):
        self._log = logging.getLogger('SOLED.SH1106Base')
        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 self._gpio is None:
            self._gpio = GPIO.get_platform_gpio()

        # RESET (RST/RES) Pin setup:
        self._rst = rst
        if not self._rst is None:
            self._gpio.setup(self._rst, GPIO.OUT)

        # Handle hardware SPI
        if spi is not None:
            self._log.debug('Using hardware SPI')
            self._spi = spi
            self._spi.set_clock_hz(8000000)

        # 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 is not None:
            self._log.debug('Using hardware I2C with custom I2C provider.')
            self._i2c = i2c.get_i2c_device(i2c_address)
        else:
            self._log.debug('Using hardware I2C with platform I2C provider.')
            import Adafruit_GPIO.I2C as I2C
            if i2c_bus is None:
                self._i2c = I2C.get_i2c_device(i2c_address)
            else:
                self._i2c = I2C.get_i2c_device(i2c_address, busnum=i2c_bus)

        # 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)
示例#8
0
文件: arduino.py 项目: vam-vam/artik
 def __init__(self, i2c_addr=None):
     try:
         if i2c_addr is None:
             self._bus = I2C.get_i2c_device(ARDUINO_I2CADDR)
         else:
             self._bus = I2C.get_i2c_device(i2c_addr)
     except Exception:
         raise RuntimeError("Error getting I2C device address")
 def get_i2c_device(self, address, i2c, i2c_bus):
     if i2c is not None:
         return i2c.get_i2c_device(address)
     else:
         import Adafruit_GPIO.I2C as I2C
         if i2c_bus is None:
             return I2C.get_i2c_device(address)
         else:
             return I2C.get_i2c_device(address, busnum=i2c_bus)
    def __init__(
        self,
        width,
        height,
        rst,
        dc=None,
        sclk=None,
        din=None,
        cs=None,
        gpio=None,
        spi=None,
        i2c_bus=None,
        i2c_address=SSD1306_I2C_ADDRESS,
        i2c=None,
    ):
        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 self._gpio is None:
            self._gpio = 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
            self._spi.set_clock_hz(8000000)
            # 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 is not None:
            self._log.debug("Using hardware I2C with custom I2C provider.")
            self._i2c = i2c.get_i2c_device(i2c_address)
        else:
            self._log.debug("Using hardware I2C with platform I2C provider.")
            import Adafruit_GPIO.I2C as I2C

            if i2c_bus is None:
                self._i2c = I2C.get_i2c_device(i2c_address)
            else:
                self._i2c = I2C.get_i2c_device(i2c_address, busnum=i2c_bus)
                # 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)
示例#11
0
class SSD1306Base(object):
    """Base class for SSD1306-based OLED displays.  Implementors should subclass
    and provide an implementation for the _initialize function.
    """

    def __init__(self, width, height, rst, dc=None, sclk=None, din=None, cs=None,
                 gpio=None, spi=None, i2c_bus=None, i2c_address=SSD1306_I2C_ADDRESS,
                 i2c=None, mcp_rst=None, mcp_address=None):
        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
        # Instantiate MCP if rst pin is in mcp.
        if mcp_rst is not None and mcp_address is not None:
            self.__mcp_rst = mcp_rst
            self.__mcp = MCP.MCP23017(mcp_address, busnum=1)
		    self.__mcp.setup(self.__mcp_rst, MCP.GPIO.OUT)
        
        if self._gpio is None:
            self._gpio = GPIO.get_platform_gpio()
        # Setup reset pin.
        self._rst = rst
        if not self._rst is None and (mcp_rst is None or mcp_address is None):
            self._gpio.setup(self._rst, GPIO.OUT)
        # Handle hardware SPI
        if spi is not None:
            self._log.debug('Using hardware SPI')
            self._spi = spi
            self._spi.set_clock_hz(8000000)
        # 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 is not None:
            self._log.debug('Using hardware I2C with custom I2C provider.')
            self._i2c = i2c.get_i2c_device(i2c_address)
        else:
            self._log.debug('Using hardware I2C with platform I2C provider.')
            if i2c_bus is None:
                self._i2c = I2C.get_i2c_device(i2c_address)
            else:
                self._i2c = I2C.get_i2c_device(i2c_address, busnum=i2c_bus)
        # 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)
示例#12
0
def get_i2c_device(address, i2c, i2c_bus):
    # Helper method to get a device at the specified address from the I2C bus.
    # If no i2c bus is specified (i2c param is None) then the default I2C bus
    # for the platform will be used.
    if i2c is not None:
        return i2c.get_i2c_device(address)
    else:
        import Adafruit_GPIO.I2C as I2C
        if i2c_bus is None:
            return I2C.get_i2c_device(address)
        else:
            return I2C.get_i2c_device(address, busnum=i2c_bus)
示例#13
0
def get_i2c_device(address, i2c, i2c_bus):
    # Helper method to get a device at the specified address from the I2C bus.
    # If no i2c bus is specified (i2c param is None) then the default I2C bus
    # for the platform will be used.
    if i2c is not None:
        return i2c.get_i2c_device(address)
    else:
        import Adafruit_GPIO.I2C as I2C
        if i2c_bus is None:
            return I2C.get_i2c_device(address)
        else:
            return I2C.get_i2c_device(address, busnum=i2c_bus)
示例#14
0
    def __init__(
        self,
        width,
        height,
        rst,
        dc=None,
        sclk=None,
        din=None,
        cs=None,
        gpio=None,
        i2c_bus=None,
        i2c_address=SSD1306_I2C_ADDRESS,
        i2c=None,
    ):
        self._log = logging.getLogger("Adafruit_SSD1306.SSD1306Base")
        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 self._gpio is None:
            self._gpio = GPIO.get_platform_gpio()

        # Setup reset pin.
        self._rst = rst
        if self._rst is not None:
            self._gpio.setup(self._rst, GPIO.OUT)

        # Handle hardware I2C
        elif i2c is not None:
            self._log.debug("Using hardware I2C with custom I2C provider.")
            self._i2c = i2c.get_i2c_device(i2c_address)
        else:
            self._log.debug("Using hardware I2C with platform I2C provider.")

            if i2c_bus is None:
                self._i2c = I2C.get_i2c_device(i2c_address)
            else:
                self._i2c = I2C.get_i2c_device(i2c_address, busnum=i2c_bus)

        # 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)
示例#15
0
 def __init__(self, busnum=0, address=_FXOS8700_ADDRESS,
              accel_range=ACCEL_RANGE_2G, **kwargs):
     assert accel_range in (ACCEL_RANGE_2G, ACCEL_RANGE_4G, ACCEL_RANGE_8G)
     self._accel_range = accel_range
     #self._device = i2c_dev.I2CDevice(i2c, address)
     self._device = I2C.get_i2c_device(address, busnum=0) #, kwargs)
     # Check for chip ID value.
     if self._read_u8(_FXOS8700_REGISTER_WHO_AM_I) != _FXOS8700_ID:
         raise RuntimeError('Failed to find FXOS8700, check wiring!')
     # Set to standby mode (required to make changes to this register)
     self._write_u8(_FXOS8700_REGISTER_CTRL_REG1, 0)
     if accel_range == ACCEL_RANGE_2G:
         self._write_u8(_FXOS8700_REGISTER_XYZ_DATA_CFG, 0x00)
     elif accel_range == ACCEL_RANGE_4G:
         self._write_u8(_FXOS8700_REGISTER_XYZ_DATA_CFG, 0x01)
     elif accel_range == ACCEL_RANGE_8G:
         self._write_u8(_FXOS8700_REGISTER_XYZ_DATA_CFG, 0x02)
     # High resolution
     self._write_u8(_FXOS8700_REGISTER_CTRL_REG2, 0x02)
     # Active, Normal Mode, Low Noise, 100Hz in Hybrid Mode
     self._write_u8(_FXOS8700_REGISTER_CTRL_REG1, 0x15)
     # Configure the magnetometer
     # Hybrid Mode, Over Sampling Rate = 16
     self._write_u8(_FXOS8700_REGISTER_MCTRL_REG1, 0x1F)
     # Jump to reg 0x33 after reading 0x06
     self._write_u8(_FXOS8700_REGISTER_MCTRL_REG2, 0x20)
示例#16
0
文件: sensor_top.py 项目: Chinmoym/BT
def readfrom(device_addr, register):
    try:
        device = I2C.get_i2c_device(device_addr)
        ans = device.readU8(register)
        return ans
    except IOError:
        return "No Device Found"
示例#17
0
    def __init__(self, address=0x40, busnum=1, **kwargs):

        # Setup I2C interface for the device.
        self.device = I2C.get_i2c_device(address, busnum=busnum, **kwargs)

        self.reset()
        self.wake()
示例#18
0
    def __init__(self,
                 shunt_ohms,
                 max_expected_amps=None,
                 busnum=1,
                 address=__ADDRESS,
                 log_level=logging.ERROR):
        """Construct the class.

        Pass in the resistance of the shunt resistor and the maximum expected
        current flowing through it in your system.

        Arguments:
        shunt_ohms -- value of shunt resistor in Ohms (mandatory).
        max_expected_amps -- the maximum expected current in Amps (optional).
        address -- the I2C address of the INA219, defaults
            to *0x40* (optional).
        log_level -- set to logging.DEBUG to see detailed calibration
            calculations (optional).
        """
        if len(logging.getLogger().handlers) == 0:
            # Initialize the root logger only if it hasn't been done yet by a
            # parent module.
            logging.basicConfig(level=log_level, format=self.__LOG_FORMAT)
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(log_level)

        self._i2c = I2C.get_i2c_device(address=address, busnum=1)
        self._shunt_ohms = shunt_ohms
        self._max_expected_amps = max_expected_amps
        self._min_device_current_lsb = self._calculate_min_current_lsb()
        self._gain = None
        self._auto_gain_enabled = False
示例#19
0
 def __init__(self, address, registers, **kwargs):
     self.address = address
     self.registers = registers
     self._sensor = I2C.get_i2c_device(address=address, busnum=1, **kwargs)
     self.enable()
     self.bias = 0
     self.variance = 0
示例#20
0
文件: si1145.py 项目: zpiman/Diaslab
 def __init__(self, options={}):
     self.options = core.mergeOptions(DEFAULT_OPTIONS, options)
     self.device = I2C.get_i2c_device(self.options["address"])
     self.value = {"uv": 0, "ir":0,"visible":0}
     self.lastUpdate = time.time()
     self._reset()
     self._load_calibration()
示例#21
0
def pca9548a_setup(pca9548a_channel):
    """
    Set i2c multiplexer (pca9548a) channel
    """
    pca9548a = I2C.get_i2c_device(PCA9548A_ADDR)
    pca9548a.writeRaw8(pca9548a_channel)
    time.sleep(0.1)
示例#22
0
    def __init__(self,
                 shunt_ohms,
                 max_expected_amps=None,
                 busnum=None,
                 address=__ADDRESS,
                 log_level=logging.ERROR):
        """ Construct the class passing in the resistance of the shunt
        resistor and the maximum expected current flowing through it in
        your system.

        Arguments:
        shunt_ohms -- value of shunt resistor in Ohms (mandatory).
        max_expected_amps -- the maximum expected current in Amps (optional).
        address -- the I2C address of the INA219, defaults
            to *0x40* (optional).
        log_level -- set to logging.DEBUG to see detailed calibration
            calculations (optional).
        """
        logging.basicConfig(level=log_level, format=self.__LOG_FORMAT)
        self._i2c = I2C.get_i2c_device(address=address, busnum=busnum)
        self._shunt_ohms = shunt_ohms
        self._max_expected_amps = max_expected_amps
        self._min_device_current_lsb = self._calculate_min_current_lsb()
        self._gain = None
        self._auto_gain_enabled = False
示例#23
0
 def __init__(self,
              busnum=0,
              address=_FXAS21002C_ADDRESS,
              gyro_range=GYRO_RANGE_250DPS):
     assert gyro_range in (GYRO_RANGE_250DPS, GYRO_RANGE_500DPS,
                           GYRO_RANGE_1000DPS, GYRO_RANGE_2000DPS)
     self._gyro_range = gyro_range
     #self._device = i2c_dev.I2CDevice(i2c, address)
     self._device = I2C.get_i2c_device(address, busnum=0)  #, kwargs)
     # Check for chip ID value.
     if self._read_u8(_GYRO_REGISTER_WHO_AM_I) != _FXAS21002C_ID:
         raise RuntimeError('Failed to find FXAS21002C, check wiring!')
     ctrl_reg0 = 0x00
     if gyro_range == GYRO_RANGE_250DPS:
         ctrl_reg0 = 0x03
     elif gyro_range == GYRO_RANGE_500DPS:
         ctrl_reg0 = 0x02
     elif gyro_range == GYRO_RANGE_1000DPS:
         ctrl_reg0 = 0x01
     elif gyro_range == GYRO_RANGE_2000DPS:
         ctrl_reg0 = 0x00
     # Reset then switch to active mode with 100Hz output
     # Putting into standy doesn't work as the chip becomes instantly
     # unresponsive.  Perhaps CircuitPython is too slow to go into standby
     # and send reset?  Keep these two commented for now:
     #self._write_u8(_GYRO_REGISTER_CTRL_REG1, 0x00)     # Standby)
     #self._write_u8(_GYRO_REGISTER_CTRL_REG1, (1<<6))   # Reset
     self._write_u8(_GYRO_REGISTER_CTRL_REG0, ctrl_reg0)  # Set sensitivity
     self._write_u8(_GYRO_REGISTER_CTRL_REG1, 0x0E)  # Active
     time.sleep(0.1)  # 60 ms + 1/ODR
示例#24
0
    def __init__(self, address=0x6a, debug=0, pause=0.8):
        self.i2c = I2C.get_i2c_device(address)
        self.address = address
        #        dataToWrite = 0
        #        dataToWrite |= 0x03
        #        dataToWrite |= 0x00
        #        dataToWrite |= 0x10
        #        self.i2c.write8(0X10, dataToWrite)

        # [FSXL BW_XL 4 bits 0001]
        dataToWrite = 0
        dataToWrite |= 0x01  # 2g [FS_XL 00] sample 200HZ BW_XL [01]
        dataToWrite |= 0x50  #208HZ sample
        self.i2c.write8(0X10, dataToWrite)

        # Settinggyro sensitivity to + / - 2000 deg /
        dataToWrite = 0
        #00: 250 dps; 01: 500 dps; 10: 1000 dps; 11: 2000 dps and sample it at 208HZ
        dataToWrite |= 0x5E  # 2g [FS_XL 00] sample 200HZ BW_XL [01]
        self.i2c.write8(0X11, dataToWrite)

        time.sleep(1)

        self.gyro = {'y': 0, 'z': 0}
        self.accel = {'x': 0, 'y': 0, 'z': 0}
        self.balance_angle = 0
        self.balance_gyro = 0
        self.turn_gyro = 0

        self.kalman = KalmanFilter()
示例#25
0
    def __init__(self,
                 shunt_ohms,
                 max_expected_amps=None,
                 busnum=None,
                 address=0x40,
                 log_level=logging.ERROR):
        """ Construct the class passing in the resistance of the shunt
        resistor and the maximum expected current flowing through it in
        your system.

        Arguments:
        shunt_ohms -- value of shunt resistor in Ohms (mandatory).
        max_expected_amps -- the maximum expected current in Amps (optional).
        address -- the I2C address of the INA219, defaults
            to *0x40* (optional).
        log_level -- set to logging.DEBUG to see detailed calibration
            calculations (optional).
        """
        self._i2c = I2C.get_i2c_device(address=address, busnum=busnum)
        self._shunt_ohms = shunt_ohms
        self._max_expected_amps = max_expected_amps
        self._min_device_current_lsb = self._calculate_min_current_lsb()
        self._gain = None
        self._auto_gain_enabled = False
        self._voltage_range = None
        try:
            self._read_voltage_register()
        except Exception:
            raise RuntimeError("INA219 does not exist.")
示例#26
0
    def __init__(self,
                 address=None,
                 busnum=None,
                 integration_time=TSL2561_INTEGRATIONTIME_402MS,
                 gain=TSL2561_GAIN_1X,
                 autogain=False,
                 debug=False):

        # Set default address and bus number if not given
        if address is not None:
            self.address = address
        else:
            self.address = TSL2561_ADDR_FLOAT
        if busnum is None:
            self.busnum = 1

        self.i2c = I2C.get_i2c_device(self.address, busnum=busnum)

        self.debug = debug
        self.integration_time = integration_time
        self.gain = gain
        self.autogain = autogain

        if self.integration_time == TSL2561_INTEGRATIONTIME_402MS:
            self.delay_time = TSL2561_DELAY_INTTIME_402MS
        elif self.integration_time == TSL2561_INTEGRATIONTIME_101MS:
            self.delay_time = TSL2561_DELAY_INTTIME_101MS
        elif self.integration_time == TSL2561_INTEGRATIONTIME_13MS:
            self.delay_time = TSL2561_DELAY_INTTIME_13MS
        self._begin()
示例#27
0
文件: sensor_top.py 项目: Chinmoym/BT
def writeto(device_addr, register, value):
    try:
        device = I2C.get_i2c_device(device_addr)
        device.write8(register, value)
        return "Write Successful"
    except IOError:
        return "No Device found"
示例#28
0
 def __init__(self, address=VCNL4010_ADDRESS, busNumber=1):
     """ Initialize the VCNL40xx sensor """
     #queue controls access to interrupts
     self.interrupt_queue = queue.Queue()
     # Setup I2C interface for the device.
     self._device = I2C.get_i2c_device(address, busNumber)
     self.gpio_pin = 23  # default pin
     self.reset()
示例#29
0
    def init_tca(self):
        self.tca = I2C.get_i2c_device(address=0x70)

        self.tca_select(0)
        self.tca_select(1)

        self.select_disp('all disp mobilize')
        self.texts([1, 'f**k'])
 def __init__(self, address=0x39, debug=0, pause=0.8):
 
     self.i2c = I2C.get_i2c_device(address)
     self.address = address
     self.pause = pause
     self.debug = debug
     self.gain = 0 # no gain preselected
     self.i2c.write8(0x80, 0x03)     # enable the device
示例#31
0
文件: bmp180.py 项目: zpiman/Diaslab
    def __init__(self, options={}):
        self.options = core.mergeOptions(DEFAULT_OPTIONS, options)
        self.device = I2C.get_i2c_device(self.options["address"])

        self.valueLock = threading.Lock()
        self.value = {"pressure": 0, "temperature": 0}
        self.lastUpdate = time.time()

        self._setup()
示例#32
0
    def __init__(self, address=AM2315_I2CADDR, i2c=None, **kwargs):
#        if i2c is None:
#            import Adafruit_GPIO.I2C as I2C
#            i2c = I2C
#        self._device = i2c.get_i2c_device(address, **kwargs)
        self._device = I2C.get_i2c_device(address, busnum=0, **kwargs)
        self._logger = logging.getLogger('am2315.AM2315')
        self.humidity = 0
        self.temperature = 0
示例#33
0
 def address(self, value):
     if (value < IQS5xx_DEFAULT_ADDRESS) or (value > IQS5xx_MAX_ADDRESS):
         raise ValueError(
             "Invalid I2C Address. Use something in the range [%x, %x]" %
             (IQS5xx_DEFAULT_ADDRESS, IQS5xx_MAX_ADDRESS))
     self.__address = value
     self._device = i2c.get_i2c_device(value)
     self._logger = logging.getLogger(
         'IQS5xx.Address.{0:#0X}'.format(value))
示例#34
0
 def __init__(self, controller, timeout=1, address=AMG88xx_I2CADDR, bus=1, name="IR1"):
     super().__init__()
     self._controller = controller
     controller.register_sensor(self, name)
     self._timeout = timeout
     self._run = False
     self._active = False
     self._name = name
     self._device = I2C.get_i2c_device(address, busnum=bus)
示例#35
0
 def __init__(self, name, mplx_id, address=0x68):
     power_mgmt_1 = 0x6b  # register power management of IMU
     self.name = name
     self.mplx_id = mplx_id  # plex ID of IMU
     # MultiPlexer schlaten, um das Modul ansprechen zu koennen
     self.i2c = Adafruit_I2C.get_i2c_device(address, busnum=2)
     self.plexer.select(self.mplx_id)
     time.sleep(.1)
     # Power on of Acc
     self.i2c.write8(power_mgmt_1, 0x00)
示例#36
0
    def __init__(self, width, height, rst, dc=None, sclk=None, din=None, cs=None, gpio=None,
                 spi=None, i2c_bus=None, i2c_address=SSD1306_I2C_ADDRESS,
                 i2c=None):
        self._spi = None
        self._i2c = None
        self.width = width
        self.height = height
        self._pages = height // 8
        self._buffer = [0] * width * self._pages
        self._cursor = 0

        # Default to platform GPIO if not provided.
        self._gpio = gpio
        if self._gpio is None:
            self._gpio = 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._spi = spi
            self._spi.set_clock_hz(8000000)
        # Handle software SPI
        elif sclk is not None and din is not None and cs is not None:
            self._spi = SPI.BitBang(self._gpio, sclk, din, None, cs)
        # Handle hardware I2C
        elif i2c is not None:
            self._i2c = i2c.get_i2c_device(i2c_address)
        else:
            import Adafruit_GPIO.I2C as I2C

            self._i2c = I2C.get_i2c_device(i2c_address) if i2c_bus is None else I2C.get_i2c_device(i2c_address,
                                                                                                   busnum=i2c_bus)

        # 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)
示例#37
0
    def __init__(self, busnum=None):
        # Each feature is given a call name. Although The magnetometer and
        # accelerometer use the same address, they've been given different
        # names for clarity.
        self.mag    = I2C.get_i2c_device(self.LSM9DS0_MAG_ADDRESS, busnum)
        self.accel  = I2C.get_i2c_device(self.LSM9DS0_ACCEL_ADDRESS, busnum)
        self.gyro   = I2C.get_i2c_device(self.LSM9DS0_GYRO_ADDRESS, busnum)

        # Magnetometer initialisation
        self.mag.write8(self.LSM9DS0_CTRL_REG5_XM, 0b11110000) # Temperature sensor enabled, high res mag, 50Hz
        self.mag.write8(self.LSM9DS0_CTRL_REG6_XM, 0b01100000) # +/- 12 gauss
        self.mag.write8(self.LSM9DS0_CTRL_REG7_XM, 0b00000000) # Normal mode, continuous-conversion mode

        # Accelerometer initialisation
        self.accel.write8(self.LSM9DS0_CTRL_REG1_XM, 0b01100111) # 100Hz, XYZ enabled
        self.accel.write8(self.LSM9DS0_CTRL_REG2_XM, 0b00100000) # +/- 16 g

        # Gyro initialisation
        self.gyro.write8(self.LSM9DS0_CTRL_REG1_G, 0b00001111) # Normal power mode, XYZ enabled
        self.gyro.write8(self.LSM9DS0_CTRL_REG4_G, 0b00110000) # Continuous update, 2000 dps
示例#38
0
   def __init__(self, gyro_dr=(LSM9DS0_GYRODR_95HZ | LSM9DS0_GYRO_CUTOFF_1), gyro_scale=LSM9DS0_GYROSCALE_245DPS, gyro_addr=LSM9DS0_GYRO_ADDR):
      """looks for the lsm9dso on i2c bus, and performs register configuration on it"""
      self._sensor = i2c.get_i2c_device(gyro_addr)
      
      #verify initialization by checking the who_am_i register
      if not (self._sensor.readU8(LSM9DS0_REG_WHO_AM_I_G) == LSM9DS0_GYRO_ID):
         #not the right device!
         print "Could not initialize the gyro!"
         #sys.exit()

      self.start_capture()
      self._config_gyro(gyro_scale, gyro_dr)
 def __init__(self, address=0x6b, debug=0, pause=0.8):
     self.i2c = I2C.get_i2c_device(address)
     self.address = address
     dataToWrite = 0 #Start Fresh!
     dataToWrite |= 0x03 # set at 50hz, bandwidth
     dataToWrite |= 0x00  # 2g accel range
     dataToWrite |= 0x10 # 13hz ODR
     self.i2c.write8(0X10, dataToWrite) #writeRegister(LSM6DS3_ACC_GYRO_CTRL2_G, dataToWrite);
     
     accel_center_x = self.i2c.readS16(0X28)
     accel_center_y = self.i2c.readS16(0x2A)
     accel_center_z = self.i2c.readS16(0x2C)
示例#40
0
    def __init__(self, address=None, busnum=None,
                 integration_time=TSL2561_DELAY_INTTIME_402MS,
                 gain=TSL2561_GAIN_1X, autogain=False, debug=False):
        if address is not None:
            self.address = address
        else:
            self.address = TSL2561_ADDR_FLOAT

        self.i2c = I2C.get_i2c_device(self.address, busnum=busnum)

        self.debug = debug
        self.integration_time = integration_time
        self.gain = gain
        self.autogain = autogain

        self._begin()
 def __init__(self, address=0x53, debug=0, pause=0.8):
     self.i2c = I2C.get_i2c_device(address)
     self.address = address
     self.i2c.write8(0x2D, 0x08) #ADXL345_REG_POWER_CTL 0x2D
     
     dataToWrite = 0 #Start Fresh!
     dataToWrite |= 0b00
     self.i2c.write8(0X31, dataToWrite) #ADXL345_REG_DATA_FORMAT 0x31 2g
     
     dataToWrite = 0 #Start Fresh!
     dataToWrite |= 0b0101
     self.i2c.write8(0x2C, dataToWrite) #ADXL345_REG_DATA_FORMAT 0x31 2g
     
     accel_center_x = self.i2c.readS16(0X32)
     accel_center_y = self.i2c.readS16(0X34)
     accel_center_z = self.i2c.readS16(0X36)
示例#42
0
   def __init__(self, accel_dr=LSM9DS0_ACCELDR_50HZ, mag_dr=LSM9DS0_MAGDR_50HZ, accel_range=LSM9DS0_ACCELRANGE_16G, mag_gain=LSM9DS0_MAGGAIN_2GAUSS, addr=LSM9DS0_ACCEL_ADDR):
      """setup for the accelerometer portion of the lsm9ds0"""
      self._sensor = i2c.get_i2c_device(addr)
      
      #verify initialization by checking the who_am_i register
      if not (self._sensor.readU8(LSM9DS0_REG_WHO_AM_I_XM) == 0x49):
         #not the right device!
         print "Could not initialize the accelerometer!"
         #sys.exit()

      #turn on the 3 axis for both ones
      self.start_capture() 
      
      #set read frequency
      self._config_accel(accel_dr, accel_range)
      self._config_magnetometer(mag_dr, mag_gain)
示例#43
0
    def __init__(self, ahrs, update_rate_hz, busnum=None, i2c_interface=None, **kwargs):
        self.i2c = I2C.get_i2c_device(0x32, busnum, i2c_interface, **kwargs)

        self.update_rate_hz = update_rate_hz
        self.running = True

        self.ahrs = ahrs
        self.raw_data_update = GyroUpdate()
        self.ahrs_update = AHRSUpdate()
        self.ahrspos_update = AHRSPosUpdate()
        self.board_id = BoardID()
        self.board_state = BoardState()

        self.last_sensor_timestamp = 0

        self.last_update_time = 0.0
        self.byte_count = 0
        self.update_count = 0
def init():
    '''
    Clear the screen
    '''
    global i2c_bus
    global image
    global draw
    global font
    global fix_font
    if i2c_bus == None:
        i2c_bus = I2C.get_i2c_device(0x3C)
        command(SSD1306_DISPLAYOFF)                    # 0xAE
        command(SSD1306_SETDISPLAYCLOCKDIV)            # 0xD5
        command(0x80)                                  # the suggested ratio 0x80
        command(SSD1306_SETMULTIPLEX)                  # 0xA8
        command(0x3F)
        command(SSD1306_SETDISPLAYOFFSET)              # 0xD3
        command(0x0)                                   # no offset
        command(SSD1306_SETSTARTLINE | 0x0)            # line #0
        command(SSD1306_CHARGEPUMP)                    # 0x8D
        command(0x14)
        command(SSD1306_MEMORYMODE)                    # 0x20
        command(0x00)                                  # 0x0 act like ks0108
        command(SSD1306_SEGREMAP | 0x1)
        command(SSD1306_COMSCANDEC)
        command(SSD1306_SETCOMPINS)                    # 0xDA
        command(0x12)
        command(SSD1306_SETCONTRAST)                   # 0x81
        command(0xCF)
        command(SSD1306_SETPRECHARGE)                  # 0xd9
        command(0xF1)
        command(SSD1306_SETVCOMDETECT)                 # 0xDB
        command(0x40)
        command(SSD1306_DISPLAYALLON_RESUME)           # 0xA4
        command(SSD1306_NORMALDISPLAY)                 # 0xA6
        command(SSD1306_DISPLAYON)
        image = Image.new('1', (WIDTH, HEIGHT))
        draw = ImageDraw.Draw(image)       
        if fix_font:
            font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf", 10)
        else:
            font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 9)
    draw.rectangle((0, 0, WIDTH, HEIGHT), outline=0, fill=0)
示例#45
0
off = 0xAE
invert = 0xA7
no_invert = 0xA6
vertical_flip = 0xC8
no_vertical_flip = 0xC0
all_on = 0xA5
no_all_on = 0xA4
set_brightness = 0x81
set_column = 0x21
set_page = 0x22
set_high_column = 0x00
set_low_column = 0x10
set_start_line = 0x40
set_vertical_offset = 0xD3 # the number of pixels to wrap picture down

port = I2C.get_i2c_device(address)

buffer = Image.new('1', (128, 64))
temp_buffer = Image.new('1', (128, 64))
console_buffer = Image.new('1', (128, 64))
draw = ImageDraw.Draw(buffer)
console_draw = ImageDraw.Draw(console_buffer)
font8 = ImageFont.truetype("Minecraftia.ttf", 8)
font16 = ImageFont.truetype("Minecraftia.ttf", 16)
font24 = ImageFont.truetype("Minecraftia.ttf", 24)
font = font8 # font to actually display with. can be changed to font8/16/24
font_size = 8
old_cursor_line = 0

def command(hex):
	'''Sends hexadecimal value to OLED as a command eg. Oled.on.'''
示例#46
0
#!/usr/bin/env python
import Adafruit_GPIO.I2C as i2c#Imports adafruit library for sensors
import requests # imports web library
from time import sleep, time # Imports time and sleep


requests.packages.urllib3.disable_warnings() # handles warnings from requests

address = 0x27 # Device Address
try:
	device = i2c.get_i2c_device(address)# get device address
	print('PI Temperature Sensor Running')
	while True:
		try:
			read_results = device.readList(0,4)#read results
			temp = (64.0*int(read_results[2])+int(read_results[3])/4)/(2**14-1)*165-40#Converts temp to C
			hum = ((256.0*int(read_results[0])+int(read_results[1]))/(2**14-1)%1)*100# Gets humindity 
			#url = "http://178.62.91.44:3001/sensor/1?temp_value="+str(temp)+"&hum_value="+str(hum)+"&time="+str(int(time()))#declare uri template and format
			url = "http://178.62.91.44:30002/sensor/1?value="+str(temp)+"&time="+str(int(time()))
			r = requests.put(url,verify=False)#sends data to server via requests
			print ('Sending Temp: ' + '%.2f'%round(temp,2)) #prints temp
			sleep(60)#Update EveryMinute
			#if r.status_code == 200:
			#	print ('Success')
		except:
			print('An Error Sending data has occurred, Check Server, Trying again in 30 seconds')
			sleep(30)
except:
	print("An Error Has Occured With the Sensor Configuration")
	
	
示例#47
0
文件: gps.py 项目: Knio/gps_tracker
import time

import Adafruit_GPIO.I2C as i2c
import pynmea2

dev = i2c.get_i2c_device(busnum=2, address=0x42)

def read():
    hi = dev.readU8(0x7d)
    lo = dev.readU8(0x7e)
    nbytes = (hi << 8) | lo
    print('reading %d bytes' % nbytes)
    return ''.join(chr(dev.readU8(0xff)) for i in range(nbytes))

def read2():
    hi = dev.readU8(0x7d)
    lo = dev.readU8(0x7e)
    nbytes = (hi << 8) | lo
    line = []
    while 1:
        b = dev.readU8(0xff)
        if b == 0xff: break
        c = chr(b)
        if c == '\n': break
        line.append(c)
    return (nbytes, ''.join(line))

while 1:
    nb, line = read2()
    try:
        msg = pynmea2.parse(line)