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, 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 _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)
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 __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)
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)
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)
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 activate_ready(): """ swaps the high and low threshold registers so that the conversion ready pin will be activated on the ADC """ high = I2C.reverseByteOrder(0x8000) low = I2C.reverseByteOrder(0x7fff) D.dut.write16(D.highThreshReg, high) D.dut.write16(D.lowThreshReg,low)
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)
def _load_calibration(self): #load calibration self._device.write16( TMP007_CONFIG, I2C.reverseByteOrder(TMP007_CFG_MODEON | TMP007_CFG_ALERTEN | TMP007_CFG_TRANSC | self._mode)) #set alert status self._device.write16( TMP007_STATMASK, I2C.reverseByteOrder(TMP007_STAT_ALERTEN | TMP007_STAT_CRTEN))
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()
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)
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()
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)
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, 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)
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)
def _configure_logging(self): logging.basicConfig(level=logging.WARNING, format='%(asctime)-15s %(levelname)-5s %(message)s') # TODO put log configuration in a (yaml) config file # The basic config doesn't hold through tests radio_logger = logging.getLogger("RPiNWR") radio_logger.setLevel(logging.DEBUG) radio_log_handler = logging.FileHandler("radio.log", encoding='utf-8') radio_log_handler.setFormatter(logging.Formatter(fmt='%(asctime)-15s %(levelname)-5s %(message)s', datefmt="")) radio_log_handler.setLevel(logging.DEBUG) radio_logger.addHandler(radio_log_handler) message_logger = logging.getLogger("RPiNWR.same.message") message_logger.setLevel(logging.DEBUG) message_log_handler = logging.FileHandler("messages.log", encoding='utf-8') message_log_handler.setFormatter(logging.Formatter(datefmt="")) message_log_handler.setLevel(logging.DEBUG) # DEBUG=test, INFO=watches & emergencies, WARN=warnings message_logger.addHandler(message_log_handler) # Since this is logging lots of things, best to not also log every time we check for status try: import Adafruit_GPIO.I2C as i2c i2cLogger = logging.getLogger('Adafruit_I2C.Device.Bus.{0}.Address.{1:#0X}' .format(i2c.get_default_bus(), 0x11)) except ImportError: i2cLogger = logging.getLogger( 'Adafruit_I2C.Device.Bus') # a little less specific, but probably just as good i2cLogger.addFilter(Radio.exclude_routine_status_checks)
def write_config(): """ Write the desired options to the ADC configuration register. Get data from global options """ global D # bit shift everything into its right place in the message. Check datasheet. # Some options were not broken out for changing. The "magic bits" are # those options. Combine all the options through bit-wise OR newConfig = ( 1 << 15 | # OS - trigger conversion D.mux << 12 | # MUX D.pga << 9 | # PGA 1 << 8 | # MODE - singal shot D.dr << 5 | # DR 0 << 4 | # COMP_MODE 0 << 3 | # COMP_POL 0 << 2 | # COMP_LAT 0 << 1 ) # COMP_QUE # print "mux: ", bin(D.mux) # print "pga: ", bin(D.pga) # print "dr: ", bin(D.dr) # due to something with byte-writing order, we need to flip # the bytes before writing. I don't know the full details # print "config: %s"%bin(newConfig) # print "length: %d"%len(bin(newConfig)) rev = I2C.reverseByteOrder(newConfig) # print "Reversed byte order: ", bin(rev) # write it! D.dut.write16(D.configReg,rev)
def __init__(self, address=0x20, busnum=I2C.get_default_bus(), cols=16, lines=2): """Initialize the character LCD plate. Can optionally specify a separate I2C address or bus number, but the defaults should suffice for most needs. Can also optionally specify the number of columns and lines on the LCD (default is 16x2). """ # Configure MCP23017 device. self._mcp = MCP.MCP23017(address=address, busnum=busnum) # Set LCD R/W pin to low for writing only. self._mcp.setup(LCD_PLATE_RW, GPIO.OUT) self._mcp.output(LCD_PLATE_RW, GPIO.LOW) # Set buttons as inputs with pull-ups enabled. for button in (SELECT, RIGHT, DOWN, UP, LEFT): self._mcp.setup(button, GPIO.IN) self._mcp.pullup(button, True) # Initialize LCD (with no PWM support). super(Adafruit_CharLCDPlate, self).__init__(LCD_PLATE_RS, LCD_PLATE_EN, LCD_PLATE_D4, LCD_PLATE_D5, LCD_PLATE_D6, LCD_PLATE_D7, cols, lines, LCD_PLATE_RED, LCD_PLATE_GREEN, LCD_PLATE_BLUE, enable_pwm=False, gpio=self._mcp)
def __init__(self, address=MCP9808_I2CADDR_DEFAULT, busnum=I2C.get_default_bus()): """Initialize MCP9808 device on the specified I2C address and bus number. Address defaults to 0x18 and bus number defaults to the appropriate bus for the hardware. """ self._logger = logging.getLogger('Adafruit_MCP9808.MCP9808') self._device = I2C.Device(address, busnum)
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.")
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)
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.")
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()
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()
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()
def dry_sensor(self): """ Cribbed from the Adafruit Arduino code. Guess it makes sure the sensor is ready for reading after normalizing in a room. """ orig_config = self._device.readU16BE(HDC1000_CONFIG) # reset, heat up, and select 14 bit temp & humidity # new_config = I2C.reverseByteOrder(HDC1000_CONFIG_RST | HDC1000_CONFIG_HEAT | HDC1000_CONFIG_MODE | HDC1000_CONFIG_TRES_14 | HDC1000_CONFIG_HRES_14) self._device.write16(HDC1000_CONFIG, new_config) time.sleep(0.015) # Take 1000 readings and toss the results. # for i in range(1000): self._read32(HDC1000_TEMP) time.sleep(0.001) # Write our original config back out to the device. # self._device.write16(HDC1000_CONFIG, orig_config) time.sleep(0.015)
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()
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
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)
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."
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
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"
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"
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
def set_config(self): """Set the 16 bit Big Endian INA219 configuration register (0x00) """ reg_00 = self.reg_00 if self.host_endian_is_little: reg_00 = I2C.reverseByteOrder(reg_00) self.device.write16(0x00, reg_00)
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()
def reset(self): """ reset, and select 14 bit temp & humidity """ self._device.write16(HDC1000_CONFIG, I2C.reverseByteOrder(HDC1000_CONFIG_RST | HDC1000_CONFIG_MODE | HDC1000_CONFIG_TRES_14 | HDC1000_CONFIG_HRES_14)) time.sleep(0.015)
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)
def __init__(self, mode=BMP280_STANDARD, address=BMP280_I2CADDR, busnum=I2C.get_default_bus()): self._logger = logging.getLogger('Adafruit_BMP.BMP280') # Check that mode is valid. if mode not in [BMP280_ULTRALOWPOWER, BMP280_STANDARD, BMP280_HIGHRES, BMP280_ULTRAHIGHRES]: raise ValueError('Unexpected mode value {0}. Set mode to one of BMP280_ULTRALOWPOWER, BMP280_STANDARD, BMP280_HIGHRES, or BMP280_ULTRAHIGHRES'.format(mode)) self._mode = mode # Create I2C device. self._device = I2C.Device(address, busnum) # Load calibration values. self._load_calibration()
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
def begin(self, address=MPR121_I2CADDR_DEFAULT, i2c=None, **kwargs): """Initialize communication with the MPR121. Can specify a custom I2C address for the device using the address parameter (defaults to 0x5A). Optional i2c parameter allows specifying a custom I2C bus source (defaults to platform's I2C bus). Returns True if communication with the MPR121 was established, otherwise returns False. """ # Assume we're using platform's default I2C bus if none is specified. if i2c is None: import Adafruit_GPIO.I2C as I2C i2c = I2C # Require repeated start conditions for I2C register reads. Unfortunately # the MPR121 is very sensitive and requires repeated starts to read all # the registers. I2C.require_repeated_start() # Save a reference to the I2C device instance for later communication. self._device = i2c.get_i2c_device(address, **kwargs) return self._reset()
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=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()
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)
def __init__(self, address=0x20, busnum=I2C.get_default_bus(), cols=16, lines=2): """Initialize the character LCD plate. Can optionally specify a separate I2C address or bus number, but the defaults should suffice for most needs. Can also optionally specify the number of columns and lines on the LCD (default is 16x2). """ # Configure the MCP23008 device. self._mcp = MCP.MCP23008(address=address, busnum=busnum) # Initialize LCD (with no PWM support). super(Adafruit_CharLCDBackpack, self).__init__(LCD_BACKPACK_RS, LCD_BACKPACK_EN, LCD_BACKPACK_D4, LCD_BACKPACK_D5, LCD_BACKPACK_D6, LCD_BACKPACK_D7, cols, lines, LCD_BACKPACK_LITE, enable_pwm=False, gpio=self._mcp)
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)
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)
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, 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__(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(): ''' 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)