我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用smbus.SMBus()。
def _init(): global _t_poll, _bus if _bus is not None: return _bus = smbus.SMBus(1) _bus.write_byte_data(ADDR, REG_CONFIG, 0b00011111) _bus.write_byte_data(ADDR, REG_POLARITY, 0b00000000) _bus.write_byte_data(ADDR, REG_OUTPUT, 0b00000000) _t_poll = Thread(target=_run) _t_poll.daemon = True _t_poll.start() set_pixel(0, 0, 0) atexit.register(_quit)
def _write_device_state(state): """INTERNAL. Send the state bits across the I2C bus""" try: PTLogger.debug("Connecting to bus...") i2c_bus = SMBus(_bus_id) state_to_send = 0x0F & state PTLogger.debug("Writing new state: " + _get_bit_string(state_to_send)) i2c_bus.write_byte_data(_device_addr, 0, state_to_send) result = _verify_device_state(state_to_send) if result is True: PTLogger.debug("OK") else: PTLogger.warning("Error: New state could not be verified") return result except: PTLogger.warning("Error: There was a problem writing to the device") return False
def __init__(self, bus_number=None): """Initialize i2c communication with the sensor and sets default parameters. Default parameters: continuous integration (not started) with 12ms cycles, gain 1x, pre-scale 1. :param bus_number: the i2c bus number (usually 0 or 1, depending on the hardware). Use the i2cdetect command line tool to identify the right bus. If set to None, will use the Raspberry Pi revision number to guess which bus to use. """ if bus_number is None: # Use Rasbperry Pi revision to choose bus number board_revision = RPi.GPIO.RPI_REVISION if board_revision == 2 or board_revision == 3: bus_number = 1 else: bus_number = 0 self.bus = smbus.SMBus(bus_number) self.use_continuous_integration() self.set_gain_and_prescaler(1, 1)
def _set_write_to_v1_speaker_enabled(address, enable): global _I2C_BUS if enable: PTLogger.info("Enabling write to pi-topSPEAKER (" + str(address) + ")") else: PTLogger.info("Disabling write to pi-topSPEAKER (" + str(address) + ")") try: _I2C_BUS = SMBus(_BUS_ID) value = 0x01 if enable else 0x00 _I2C_BUS.write_byte_data(address, _v1_i2c_ce_reg, value) except Exception as e: PTLogger.info("Failed to write to pi-topSPEAKER: " + str(e)) return False return True
def getTempC(): # SI7021 address, 0x40(64) # 0xF3(243) Select temperature NO HOLD master mode bus = smbus.SMBus(1) bus.write_byte(0x40, 0xF3) time.sleep(0.3) # SI7021 address, 0x40(64) # Read data back, 2 bytes, Temperature MSB first data0 = bus.read_byte(0x40) data1 = bus.read_byte(0x40) # Convert the data cTemp = ((data0 * 256 + data1) * 175.72 / 65536.0) - 46.85 #fTemp = cTemp * 1.8 + 32 print ("Temperature in Celsius is : %.2f C" %cTemp) #print ("Temperature in Fahrenheit is : %.2f F" %fTemp) return cTemp
def __init__(self, bus=1, address=0x14): """Create a new PiJuice instance. Bus is an optional parameter that specifies the I2C bus number to use, for example 1 would use device /dev/i2c-1. If bus is not specified then the open function should be called to open the bus. """ I2C_SLAVE = 0x0703 # Use this slave address I2C_SLAVE_FORCE = 0x0706 # Use this slave address, even if # is already in use by a driver! I2C_PEC = 0x0708 # != 0 to use PEC with SMBus self.i2cbus=SMBus(bus) self.addr=address #self._device = open('/dev/i2c-{0}'.format(bus), 'r+b', buffering=0) #ioctl(self._device.fileno(), I2C_SLAVE_FORCE, self.addr & 0x7F) self.t = None self.comError = False self.errTime = 0
def __init__(self, i2c_bus_number, i2c_bus_address): super(MD25MotorDriver, self).__init__() self.prev_encoder_count_1 = 0 self.prev_encoder_count_2 = 0 self.encoder_count_1 = 0 self.encoder_count_2 = 0 self.prev_delta_encoder_count_1 = 0 self.prev_delta_encoder_count_2 = 0 self.i2c_bus_address = i2c_bus_address self.i2c_bus = smbus.SMBus(i2c_bus_number) self.reset_encoders() self.i2c_bus.write_byte_data(self.i2c_bus_address, 15, 1) self.i2c_bus.write_byte_data(self.i2c_bus_address, 16, 48) self.i2c_bus.write_byte_data(self.i2c_bus_address, 14, 10)
def __init__(self, address): self.ADDRESS = address self.CMD_SEND_STRING = 0x01 self.CMD_SEND_CHAR = 0x02 self.CMD_MOUSE_MOVE = 0x03 self.CMD_WHO = 0x04 self.CMD_MOUSE_CLICK = 0x06 self.RESP_WHO = {0x00 : 'Unknown board/Command unknown', 0xA1 : 'Arduino Leonardo', 0xA2 : 'Arduino Micro', 0xB3 : 'Teensy 2.0', 0xB4 : 'Teensy++ 2.0', 0xB5 : 'Teensy 3.0', 0xB6 : 'Teensy 3.1 / 3.2', 0xB7 : 'Teensy LC', } self.response = 0 # for RPI version 1, use "bus = smbus.SMBus(0)" try: self.bus = smbus.SMBus(1) except: print "No I2C install" sys.exit(1)
def _init_connection(self): self.bus = SMBus(self._port) if self._i2c_expander == 'PCF8574': c.msleep(50) elif self._i2c_expander in ['MCP23008', 'MCP23017']: # Variable for storing data and applying bitmasks and shifting. self._mcp_data = 0 # Set iodir register value according to expander # If using MCP23017 set which gpio bank to use, A or B if self._i2c_expander == 'MCP23008': IODIR = MCP23008_IODIR self._mcp_gpio = MCP23008_GPIO elif self._i2c_expander == 'MCP23017': # Set gpio bank A or B if self._expander_params['gpio_bank'] == 'A': IODIR = MCP23017_IODIRA self._mcp_gpio = MCP23017_GPIOA elif self._expander_params['gpio_bank'] == 'B': IODIR = MCP23017_IODIRB self._mcp_gpio = MCP23017_GPIOB # Set IO DIRection to output on all GPIOs (GP0-GP7) self.bus.write_byte_data(self._address, IODIR, 0x00)
def __init__(self, busNum): #print "init PCF8591" if busNum == 0: self.__bus = SMBus(0) # on a Rev 1 board #print "bus 0" else: self.__bus = SMBus(1) # on a Rev 2 board self.__addr = self.__checkI2Caddress(0x48) self.__DACEnabled = 0x00 print self.readADC() # dummy call to raise exception if no chip presnt on the i2c bus print "PCF8591 init completed" # self.__bus = __i2cBus # self.__addr = self.__checkI2Caddress(__addr) # self.__DACEnabled = 0x00 # i2c = SMBus(0) # on a Rev 1 board # # i2c = SMBus(1) # if on a Rev 2 board # # Create a PCF8591P object # sensor = PCF8591P(i2c, 0x48) # Read single ADC Channel
def __init__(self, address=DEFAULT_ADDRESS, bus=None, sensor_range=RANGE_4G, data_rate=BW_RATE_400HZ, debug=False): if debug: logger.setLevel(logging.DEBUG) self.i2c_address = address if bus is None: bus = self.get_pi_revision() # bcm2708 doesnt support repeated start bits for i2c messages. # set the combined parameter which sends command correctly. # **********WARNING******************* # axes data seems to have lot of noise and its a hack. os.chmod(BCM2708_COMBINED_PARAM_PATH, 666) os.system('echo -n 1 > {!s}'.format(BCM2708_COMBINED_PARAM_PATH)) # ************************************ self._smbus = smbus.SMBus(bus) self.sensor_range = sensor_range self.data_rate = data_rate self.high_res_mode = OVERSAMPLING_MODE self.setup_sensor()
def get_smbus(): candidates = [] prefix = '/dev/i2c-' for bus in glob.glob(prefix + '*'): try: n = int(bus.replace(prefix, '')) candidates.append(n) except: pass if len(candidates) == 1: return smbus.SMBus(candidates[0]) elif len(candidates) == 0: raise Exception("Could not find an I2C bus") else: raise Exception("Multiple I2C busses found")
def get_smbus(self): # detect i2C port number and assign to i2c_bus i2c_bus = 0 for line in open('/proc/cpuinfo').readlines(): m = re.match('(.*?)\s*:\s*(.*)', line) if m: (name, value) = (m.group(1), m.group(2)) if name == "Revision": if value[-4:] in ('0002', '0003'): i2c_bus = 0 else: i2c_bus = 1 break try: return smbus.SMBus(i2c_bus) except IOError: print ("Could not open the i2c bus.")
def initAccel(address): global i2cBus i2cBus = smbus.SMBus(BUS_NUMBER) # init i2cBus.write_i2c_block_data(address, 0x2d, [0x00,]) # range = +-2g, Left Justify, 10-bit mode(but will ignore tha right 2-bit) i2cBus.write_i2c_block_data(address, 0x31, [0x04,]) # setings for tap (values are from data sheet) i2cBus.write_i2c_block_data(address, 0x1d, [0x60,]) i2cBus.write_i2c_block_data(address, 0x21, [0x20,]) i2cBus.write_i2c_block_data(address, 0x22, [0x20,]) i2cBus.write_i2c_block_data(address, 0x23, [0x80,]) # enable tap detection i2cBus.write_i2c_block_data(address, 0x2a, [0x07,]) i2cBus.write_i2c_block_data(address, 0x2e, [0x60,]) # start measurement i2cBus.write_i2c_block_data(address, 0x2d, [0x08,])
def i2c_scan(bus_num=1): global HAVE_SMBUS if not HAVE_SMBUS: return [] bus = smbus.SMBus(bus_num) # 1 indicates /dev/i2c-1 devices = [] for device in range(128): try: bus.read_byte(device) logger.info("Found i2c device at addr: {}".format(hex(device))) devices.append(device) except Exception: # exception if read_byte fails pass return devices # Must run some activites on the main thread, e.g. PyGame event polling
def __init__(self, name): self.bus = smbus.SMBus(1) self.name = name self.logger = com_logger.Logger(name)
def __init__(self): self.sensorAddress = 0x58 # Check before to be sure its the correct address self.device = smbus.SMBus(1) self.positions = {'found':False,'1':[0,0],'2':[0,0],'3':[0,0],'4':[0,0]} # Initialization of the IR sensor self.initCMDs = [0x30, 0x01, 0x30, 0x08, 0x06, 0x90, 0x08, 0xC0, 0x1A, 0x40, 0x33, 0x33] for i,j in zip(self.initCMDs[0::2], self.initCMDs[1::2]): self.device.write_byte_data(self.sensorAddress, i, j) sleep(0.01)
def __init__(self): self._bus = smbus.SMBus(1) self._version = sys.version_info.major self.ledYellow = 0 self.ledGreen = 0 self.ledRed = 0 self._buttonA = 0 self._buttonB = 0 self._buttonC = 0 self._fwdSpeed = 0 self._turnRate = 0 self._lockSpeeds = False self._x = 0 self._y = 0 self._phi = 0 self._lockOdometer = False self._batteryMV = 0 self._lockBattery = False self._panServo = 0 # Servo is disabled by default self._tiltServo = 0 # Servo is disabled by default self._mastServo = 0 # Servo is disabled by default self._lockServos = False self._notes = '' self._resetOdometer = True self.run() # Wait to ensure we can read/write the buffer once before starting time.sleep(.05) # Print battery level print("RPB202") print("Battery level: " + str(round(self.getBatteryVolts(), 2)) + "V")
def __init__(self, addr, port=1): self.addr = addr self.bus = smbus.SMBus(port) # Write a single command
def __init__(self, address, busnum=-1, debug=False): self.address = address # By default, the correct I2C bus is auto-detected using /proc/cpuinfo # Alternatively, you can hard-code the bus version below: # self.bus = smbus.SMBus(0); # Force I2C0 (early 256MB Pi's) # self.bus = smbus.SMBus(1); # Force I2C1 (512MB Pi's) self.bus = smbus.SMBus(busnum if busnum >= 0 else Adafruit_I2C.getPiI2CBusNumber()) self.debug = debug
def _read_device_state(): """INTERNAL. Read from the I2C bus to get the current state of the pulse. Caller should handle exceptions""" try: PTLogger.debug("Connecting to bus...") i2c_bus = SMBus(_bus_id) current_state = i2c_bus.read_byte(_device_addr) & 0x0F return int(current_state) except: PTLogger.warning("Error: There was a problem reading from the device") # Best to re-raise as we can't recover from this raise
def __init__(self, i2c_adddr=0x77): self.addr = i2c_adddr self.bus = smbus.SMBus(1) self._load_calibration()
def __init__(self, i2c_adddr=0x48): self.addr = i2c_adddr self.bus = smbus.SMBus(1)
def getHumidity(): bus = smbus.SMBus(1) bus.write_byte(0x40, 0xF5) time.sleep(0.3) # SI7021 address, 0x40(64) # Read data back, 2 bytes, Humidity MSB first data0 = bus.read_byte(0x40) data1 = bus.read_byte(0x40) # Convert the data humidity = ((data0 * 256 + data1) * 125 / 65536.0) - 6 print ("Relative Humidity is : %.2f %%" %humidity) return humidity
def __init__(self, bus_number=None, address=0x40): self.address = address if bus_number == None: self.bus_number = self._get_bus_number() else: self.bus_number = bus_number self.bus = smbus.SMBus(self.bus_number)
def __init__(self, I2C_bus_number = 1, address = 0x77): self.bus = SMBus(I2C_bus_number) self.address = address self.C1 = 0 self.C2 = 0 self.C3 = 0 self.C4 = 0 self.C5 = 0 self.C6 = 0 self.D1 = 0 self.D2 = 0 self.TEMP = 0.0 # Calculated temperature self.PRES = 0.0 # Calculated Pressure
def __init__(self, port, addr): self.addr = addr self.bus = smbus.SMBus(port) # Write a single command
def __init__(self, address=ADDR): self.address = address self._brightness = 127 self.bus = smbus.SMBus(1) self.bus.write_byte_data(self.address, CMD_MODE, MODE) self.bus.write_byte_data(self.address, CMD_OPTIONS, OPTS) self.bus.write_byte_data(self.address, CMD_BRIGHTNESS, self._brightness) self._BUF_MATRIX_1 = [0] * 8 self._BUF_MATRIX_2 = [0] * 8
def __init__(self): self.picoReg = dict() self.picoData = dict() self.i2c = smbus.SMBus(1) self.regDict = { "ledOrange": 0x09, "ledGreen": 0x0a, "ledBlue": 0x0b, "ledEnable": 0x15, } return
def __init__(self): # Program the AVR. It has a tendency to fail without the delays here. time.sleep(5) subprocess.call('/usr/local/bin/program_avr.sh') time.sleep(5) self.bus = smbus.SMBus(1) # /dev/i2c-1
def __init__(self): self.bus = smbus.SMBus(1) # /dev/i2c-1
def __init__(self, address, bus = smbus.SMBus(1)): self.address = address self.bus = bus
def __init__(self, port=1, address=0x0E, gauss=1.3, declination=(1, 57)): self.bus = smbus.SMBus(port) self.address = address (degrees, minutes) = declination self.__declDegrees = degrees self.__declMinutes = minutes self.__declination = (degrees + minutes / 60) * math.pi / 180 (reg, self.__scale) = self.__scales[gauss] # 8 Average, 15 Hz, normal measurement self.bus.write_byte_data(self.address, 0x00, 0x70) self.bus.write_byte_data(self.address, 0x01, reg << 5) # Scale # Continuous measurement self.bus.write_byte_data(self.address, 0x02, 0x00)
def __init__(self, lcd_address, lcd_width): # Define some device parameters self.I2C_ADDR = lcd_address # 0x3f I2C device address # To detect use sudo i2cdetect -y 0 # or for RPi 2 sudo i2cdetect -y 1 self.LCD_WIDTH = lcd_width # 16 or 20 Maximum characters per line print ("class LCD " + str(lcd_width)) #LCD_WIDTH = 20 OR 16 # Maximum characters per line # Define some device constants self.LCD_CHR = 1 # Mode - Sending data self.LCD_CMD = 0 # Mode - Sending command self.LCD_LINE_1 = 0x80 # LCD RAM address for the 1st line self.LCD_LINE_2 = 0xC0 # LCD RAM address for the 2nd line self.LCD_LINE_3 = 0x94 # LCD RAM address for the 3rd line self.LCD_LINE_4 = 0xD4 # LCD RAM address for the 4th line self.LCD_BACKLIGHT = 0x08 # On #LCD_BACKLIGHT = 0x00 # Off self.ENABLE = 0b00000100 # Enable bit # Timing constants self.E_PULSE = 0.0005 self.E_DELAY = 0.0005 #Open I2C interface self.bus = smbus.SMBus(0) # Rev 1 Pi uses 0 #bus = smbus.SMBus(1) # Rev 2 Pi uses 1 #def lcd_init(): # Initialise display self.lcd_byte(0x33,self.LCD_CMD) # 110011 Initialise self.lcd_byte(0x32,self.LCD_CMD) # 110010 Initialise self.lcd_byte(0x06,self.LCD_CMD) # 000110 Cursor move direction self.lcd_byte(0x0C,self.LCD_CMD) # 001100 Display On,Cursor Off, Blink Off self.lcd_byte(0x28,self.LCD_CMD) # 101000 Data length, number of lines, font size self.lcd_byte(0x01,self.LCD_CMD) # 000001 Clear display time.sleep(self.E_DELAY)
def __init__(self, addr=ADDRESS, port=1): self.addr = addr self.bus = smbus.SMBus(port)
def __init__(self, address, bus=0, debug=False): self.address = address self.bus = smbus.SMBus(bus) self.debug = debug
def __init__(self, address, busnum): """Create an instance of the I2C device at the specified address on the specified I2C bus number.""" self._address = address self._bus = smbus.SMBus(busnum) self._logger = logging.getLogger('Adafruit_I2C.Device.Bus.{0}.Address.{1:#0X}' \ .format(busnum, address))
def __init__(self, addr, port=I2CBUS): self.addr = addr self.bus = smbus.SMBus(port) # Write a single command