本文整理汇总了Python中smbus.SMBus.write_i2c_block_data方法的典型用法代码示例。如果您正苦于以下问题:Python SMBus.write_i2c_block_data方法的具体用法?Python SMBus.write_i2c_block_data怎么用?Python SMBus.write_i2c_block_data使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类smbus.SMBus
的用法示例。
在下文中一共展示了SMBus.write_i2c_block_data方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: AM2320
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import write_i2c_block_data [as 别名]
class AM2320(object):
"""
AM2320 temperature and humidity sensor class.
:param interface: I2C interface id.
:type interface: :int
:param sensor_address: AM2320 sensor I2C address. Optional, default 0x5C (92).
:type sensor_address: int
"""
def __init__(self, interface, sensor_address=0x5c):
self.interface = interface
self.address = sensor_address
self.temperature = -1000.0
self.humidity = -1
self.bus = SMBus(interface)
def _read_raw(self, command, regaddr, regcount):
try:
self.bus.write_i2c_block_data(self.address, 0x00, [])
self.bus.write_i2c_block_data(self.address, command, [regaddr, regcount])
sleep(0.002)
buf = self.bus.read_i2c_block_data(self.address, 0, 8)
except IOError, exc:
raise CommunicationError(str(exc))
buf_str = "".join(chr(x) for x in buf)
crc = unpack('<H', buf_str[-2:])[0]
if crc != self._am_crc16(buf[:-2]):
raise CommunicationError("AM2320 CRC error.")
return buf_str[2:-2]
示例2: PiGlowService
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import write_i2c_block_data [as 别名]
class PiGlowService(rpyc.Service):
def on_connect(self):
pass
def on_disconnect(self):
pass
def exposed_init(self):
self.bus = SMBus(1)
self.bus.write_byte_data(0x54, 0x00, 0x01)
self.bus.write_byte_data(0x54, 0x13, 0xFF)
self.bus.write_byte_data(0x54, 0x14, 0xFF)
self.bus.write_byte_data(0x54, 0x15, 0xFF)
def exposed_colours(self, red, orange, yellow, green, blue, white):
try:
self.bus.write_i2c_block_data(0x54, 0x01, [red, orange, yellow, green, blue, green, red, orange, yellow, white, white, blue, white, green, blue, yellow, orange, red])
self.bus.write_byte_data(0x54, 0x16, 0xFF)
except IOError:
pass
def exposed_all_off(self):
try:
self.bus.write_i2c_block_data(0x54, 0x01, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
self.bus.write_byte_data(0x54, 0x16, 0xFF)
except IOError:
pass
示例3: __init__
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import write_i2c_block_data [as 别名]
class LEDSign:
def __init__(self):
self.s = SMBus(0)
self.lock = Lock()
def print_message(self, line, message):
if len(message) > 255:
message = message[:255]
if message[:-1] != "\x00":
message = "".join([message, "\x00"])
self.print_message_loop(line, message)
def print_message_loop(self, line, message):
if message == "":
return
self.lock.acquire()
self.s.write_i2c_block_data(signAddress, line, [ord(x) for x in message[0:payLoadLen]])
self.lock.release()
self.print_message_loop(line, message[payLoadLen:])
def get_status(self):
self.lock.acquire()
labStatus = self.s.read_byte(signAddress)
self.lock.release()
return labStatus
示例4: __init__
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import write_i2c_block_data [as 别名]
class motorControlBoard:
"""Class to allow communication with the motor
control board built by me using I2C."""
__board_I2C_address = 0
def __init__(self, board_address):
if isinstance(board_address, int):
if board_address > 0 and board_address < 0x78:
self.__board_I2C_address = board_address
else:
raise Exception("Board address must be an integer between 0 and 0b1111000 (=120) exclusive.")
else:
raise Exception("Board address must be an integer.")
self.__bus = SMBus(1) # FIXME = have an option to make this zero for the old Raspberry Pis
def set_speeds(self, left_speed, right_speed):
# Enforce limits due to 8-bit resolution
if(left_speed < -0xff): left_speed = -0xff
if(left_speed > +0xff): left_speed = +0xff
# Enforce limits due to 8-bit resolution
if(right_speed < -0xff): right_speed = -0xff
if(right_speed > +0xff): right_speed = +0xff
direction = 0x00;
if(left_speed < 0): direction |= MOTOR_CONTROL_LEFT_BACK
elif(left_speed > 0): direction |= MOTOR_CONTROL_LEFT_FORE
if(right_speed < 0): direction |= MOTOR_CONTROL_RIGHT_BACK
elif(right_speed > 0): direction |= MOTOR_CONTROL_RIGHT_FORE
self.__bus.write_i2c_block_data(self.__board_I2C_address, MOTOR_CONTROL_SET_DIR_SPEED_CMD, [direction, abs(left_speed), abs(right_speed)])
示例5: __init__
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import write_i2c_block_data [as 别名]
class PiGlow:
i2c_addr = 0x54 # fixed i2c address of SN3218 ic
bus = None
def __init__(self, i2c_bus=1):
self.bus = SMBus(i2c_bus)
# first we tell the SN3218 to enable output (turn on)
self.write_i2c(CMD_ENABLE_OUTPUT, 0x01)
# then we ask it to enable each bank of LEDs (0-5, 6-11, and 12-17)
self.write_i2c(CMD_ENABLE_LEDS, [0xFF, 0xFF, 0xFF])
def update_leds(self, values):
#print "update pwm"
self.write_i2c(CMD_SET_PWM_VALUES, values)
self.write_i2c(CMD_UPDATE, 0xFF)
# a helper that writes the given value or list of values to the SN3218 IC
# over the i2c protocol
def write_i2c(self, reg_addr, value):
# if a single value is provided then wrap it in a list so we can treat
# all writes in teh same way
if not isinstance(value, list):
value = [value];
# write the data to the SN3218
self.bus.write_i2c_block_data(self.i2c_addr, reg_addr, value)
示例6: Bus_Hepler_i2c
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import write_i2c_block_data [as 别名]
class Bus_Hepler_i2c():
def __init__(self, bus_location=1):
self.bus = SMBus(bus_location)
def write_byte(self, address, register, byte):
self.bus.write_i2c_block_data(address, register, [byte])
def read_block_data(self, address, cmd):
return self.bus.read_i2c_block_data(address, cmd)
示例7: MTSMBus
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import write_i2c_block_data [as 别名]
class MTSMBus(I2CBus):
""" Multi-thread compatible SMBus bus.
This is just a wrapper of SMBus, serializing I/O on the bus for use
in multi-threaded context and adding _i2c_ variants of block transfers.
"""
def __init__(self, bus_id=1, **kwargs):
"""
:param int bus_id: the SMBus id (see Raspberry Pi documentation)
:param kwargs: parameters transmitted to :py:class:`smbus.SMBus` initializer
"""
I2CBus.__init__(self, **kwargs)
self._bus = SMBus(bus_id)
# I/O serialization lock
self._lock = threading.Lock()
def read_byte(self, addr):
with self._lock:
return self._bus.read_byte(addr)
def write_byte(self, addr, data):
with self._lock:
self._bus.write_byte(addr, data)
def read_byte_data(self, addr, reg):
with self._lock:
return self._bus.read_byte_data(addr, reg)
def write_byte_data(self, addr, reg, data):
with self._lock:
self._bus.write_byte_data(addr, reg, data)
def read_word_data(self, addr, reg):
with self._lock:
return self._bus.read_word_data(addr, reg)
def write_word_data(self, addr, reg, data):
with self._lock:
self._bus.write_word_data(addr, reg, data)
def read_block_data(self, addr, reg):
with self._lock:
return self._bus.read_block_data(addr, reg)
def write_block_data(self, addr, reg, data):
with self._lock:
self._bus.write_block_data(addr, reg, data)
def read_i2c_block_data(self, addr, reg, count):
with self._lock:
return self._bus.read_i2c_block_data(addr, reg, count)
def write_i2c_block_data(self, addr, reg, data):
with self._lock:
self._bus.write_i2c_block_data(addr, reg, data)
示例8: Device
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import write_i2c_block_data [as 别名]
class Device(object):
def __init__(self, address, bus):
self._bus = SMBus(bus)
self._address = address
def writeRaw8(self, value):
value = value & 0xff
self._bus.write_byte(self._address, value)
def readRaw8(self):
result = self._bus.read_byte(self._address) & 0xff
return result
def write8(self, register, value):
value = value & 0xff
self._bus.write_byte_data(self._address, register, value)
def readU8(self, register):
result = self._bus.read_byte_data(self._address, register) & 0xFF
return result
def readS8(self, register):
result = self.readU8(register)
if result > 127:
result -= 256
return result
def write16(self, register, value):
value = value & 0xffff
self._bus.write_word_data(self._address, register, value)
def readU16(self, register, little_endian = True):
result = self._bus.read_word_data(self._address,register) & 0xFFFF
if not little_endian:
result = ((result << 8) & 0xFF00) + (result >> 8)
return result
def readS16(self, register, little_endian = True):
result = self.readU16(register, little_endian)
if result > 32767:
result -= 65536
return result
def writeList(self, register, data):
self._bus.write_i2c_block_data(self._address, register, data)
def readList(self, register, length):
results = self._bus.read_i2c_block_data(self._address, register, length)
return results
示例9: __init__
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import write_i2c_block_data [as 别名]
class MB85RC04:
def __init__(self, I2C_bus_number = 1, address = 0x50):
self.bus = SMBus(I2C_bus_number)
self.address = address
def readByte(self, registerAddress):
if(registerAddress > 255):
self.address = self.address | 1
registerAddress = registerAddress - 256
else:
self.address = self.address & 0xFE
return self.bus.read_byte_data(self.address, registerAddress)
def writeByte(self, registerAddress, data):
if(registerAddress > 255):
self.address = self.address | 1
registerAddress = registerAddress - 256
else:
self.address = self.address & 0xFE
self.bus.write_byte_data(self.address, registerAddress, data)
def readBytes(self, registerAddress):
if(registerAddress > 255):
self.address = self.address | 1
registerAddress = registerAddress - 256
else:
self.address = self.address & 0xFE
return self.bus.read_i2c_block_data(self.address, registerAddress)
def writeBytes(self, registerAddress, data):
if(registerAddress > 255):
self.address = self.address | 1
registerAddress = registerAddress - 256
else:
self.address = self.address & 0xFE
self.bus.write_i2c_block_data(self.address, registerAddress, data)
示例10: it
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import write_i2c_block_data [as 别名]
class I2CBus:
# The device ids supported
# Note: Under linux, the enumeration of the i2c devices is not guaranteed to match the BBB device id, i.e., i2c0 may
# not map to /dev/i2c-0. Here is a link on this topic: https://datko.net/2013/11/03/bbb_i2c
# What is important from a software perspective is that pins and the device id match since we don't use the linux
# device name. That is, we need to use an id, 0, 1, 2, which corresponds to a specific device connected on specific
# pins.
# Note: I2C device 0 is not enabled by default. There is a way to enable it (see above) but there are also possible
# conflicts with existing capes.
DEV_I2C_0 = 0
DEV_I2C_1 = 1
DEV_I2C_2 = 2
# The following formatting is taken from struct and maps the character designations to number of bytes in the type
__TYPE_SIZES = {'d': 8, # double - 8 bytes
'f': 4, # float - 4 bytes
'L': 4, # uint32 - 4 bytes
'l': 4, # int32 - 4 bytes
'H': 2, # uint16 - 2 bytes
'h': 2, # int16 - 2 bytes
'B': 1, # uint8 - 1 byte
'b': 1 # int8 - 1 byte
}
def __init__(self, device):
try:
self._smbus = SMBus(device)
except RuntimeError:
raise I2CBusError("Unable to open SMBus using {}".format(device))
def _read_multiple_bytes(self, address, offset, num_bytes):
return self._smbus.read_i2c_block_data(address, offset, num_bytes)
def _write_multiple_bytes(self, address, offset, byte_values):
self._smbus.write_i2c_block_data(address, offset, list(byte_values))
def WriteUint8(self, address, offset, value):
self._smbus.write_byte_data(address, offset, value)
def WriteUint16(self, address, offset, value):
self._smbus.write_word_data(address, offset, value)
def WriteInt16(self, address, offset, value):
self._smbus.write_word_data(address, offset, value)
def WriteUint32(self, address, offset, value):
bytes = bytearray(struct.pack('L', value))
self._write_multiple_bytes(address, offset, bytes)
def WriteFloat(self, address, offset, value):
bytes = bytearray(struct.pack('f',value))
self._write_multiple_bytes(address, offset, bytes)
def WriteArray(self, address, offset, values, type, endian=sys.byteorder):
# Convert each value to its byte representation and place into a bytearray before writing to the bus
# Note: struct.pack returns a string representation of the value. For a 1-byte value, it is a
# string representation of 1 byte, for a 2 or 4 byte value, it is a 2-byte of 4-byte representation
# Therefore, it is necessary to concatentate the strings before converting to a bytearray
if endian == 'little':
format = '<'+type
else:
format = '>'+type
byte_values = ''
for value in values:
byte_values += struct.pack(format, value)
self._write_multiple_bytes(address, offset, bytearray(byte_values))
def ReadUint8(self, address, offset):
return self._smbus.read_byte_data(address, offset)
def ReadUint16(self, address, offset):
return self._smbus.read_word_data(address, offset)
def ReadInt16(self, address, offset):
return self._smbus.read_word_data(address, offset)
def ReadUint32(self, address, offset):
bytes = self._read_multiple_bytes(address, offset, I2CBus.__TYPE_SIZES['L'])
return struct.unpack('L', str(bytearray(bytes)))[0]
def ReadInt32(self, address, offset):
bytes = self._read_multiple_bytes(address, offset, I2CBus.__TYPE_SIZES['l'])
return struct.unpack('l', str(bytearray(bytes)))[0]
def ReadFloat(self, address, offset):
values = self._read_multiple_bytes(address, offset, I2CBus.__TYPE_SIZES['f'])
return struct.unpack('f', str(bytearray(values)))[0]
def ReadArray(self, address, offset, num_values, type, endian=sys.byteorder):
# Create a format specifier based on the number of values requested.
# All of the values will be read as the same type, e.g., all floats, all long, etc
# The format specifies the number of float values to convert
format = '%s%s' % (num_values, type)
# Calculate number of bytes to read
# - num_values is the number of values to read
# - num_bytes is num_values * size of each value
#.........这里部分代码省略.........
示例11: __init__
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import write_i2c_block_data [as 别名]
class ADS1015:
""" Class ro read analog values"""
#control constants
_SLAVE_ADDR = 0x48
# pointer register
_POINTER_REG_CONVERSION = 0x00
_POINTER_REG_CONFIG = 0x01
# configuration register
_CONFIG_REG_MUX_CH0 = 0x04
_CONFIG_REG_MUX_CH1 = 0x05
_CONFIG_REG_MUX_CH2 = 0x06
_CONFIG_REG_MUX_CH3 = 0x07
_CONFIG_REG_PGA_6144 = 0x00
_CONFIG_REG_PGA_4096 = 0x01
_CONFIG_REG_MODE_CONT = 0x00
_CONFIG_REG_MODE_SING = 0x01
_CONFIG_REG_DR_250SPS = 0x01
_CONFIG_REG_COMP_OFF = 0x3
def __init__(self,device_number,channel):
""" """
try:
self.bus = SMBus(device_number)
except Exception:
raise i2cError()
try:
if channel ==3:
self.CH = self._CONFIG_REG_MUX_CH3
elif channel == 2:
self.CH = self._CONFIG_REG_MUX_CH2
elif channel == 1:
self.CH = self._CONFIG_REG_MUX_CH1
else:
self.CH = self._CONFIG_REG_MUX_CH0
# MUX PGA MODE DR COMP_QUE
confList = [ self.CH, \
self._CONFIG_REG_PGA_4096, \
self._CONFIG_REG_MODE_CONT, \
self._CONFIG_REG_DR_250SPS, \
self._CONFIG_REG_COMP_OFF ]
self.configADS1015(confList)
# set conversion factor
if confList[1] == self._CONFIG_REG_PGA_6144:
self.convFactor = 6.144*2.0/4096
elif confList[1] == self._CONFIG_REG_PGA_4096:
self.convFactor = 4.096*2.0/4096
except Exception as e:
print(e)
raise ConfigError()
def configADS1015(self, list):
""" configure the chip according to list"""
MSB = (list[0]<<4)+ (list[1]<<1) + list[2]
LSB = (list[3]<<5) + list[4]
# write list to config register
self.bus.write_i2c_block_data(self._SLAVE_ADDR,self._POINTER_REG_CONFIG,[MSB, LSB])
if DEBUG:
print("configList:", list)
print("MSB: ", MSB, "LSB: ", LSB)
#read register back
Data = self.bus.read_i2c_block_data(self._SLAVE_ADDR,self._POINTER_REG_CONFIG)[:2]
#print ( "To be written: ",MSB, LSB)
print (" Read back : ",Data[0], Data[1])
def readAnalogChannel(self):
""" reads single ended analog channel"""
#read config register and overwrite MUX
configTmp = self.bus.read_i2c_block_data(self._SLAVE_ADDR,self._POINTER_REG_CONFIG)[:2]
bitmask = 0x8F
tmp = (configTmp[0] & bitmask)|(self.CH << 4)
self.bus.write_i2c_block_data(self._SLAVE_ADDR,self._POINTER_REG_CONFIG,[tmp,configTmp[1]])
# get conversion value
tmp = self.bus.read_i2c_block_data(self._SLAVE_ADDR,self._POINTER_REG_CONVERSION)[:2]
val = ((tmp[0] << 8) + tmp[1]) >> 4
return val * self.convFactor
示例12: Mpl3115a2
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import write_i2c_block_data [as 别名]
class Mpl3115a2(object):
_bus = None
def __init__(self, i2c_bus=0):
"""
:type i2c_bus: int specifying i2c bus number
"""
self._bus = SMBus(i2c_bus)
whoami = self._bus.read_byte_data(MPL3115A2_ADDRESS, MPL3115A2_WHOAMI)
if whoami != 0xc4:
print("MPL3115A2 not active.")
exit(1)
# Set MPL3115A2 oversampling to 128, put in Barometer mode, enabled standby on CTRL_REG1
self._bus.write_byte_data(
MPL3115A2_ADDRESS,
MPL3115A2_CTRL_REG1,
MPL3115A2_CTRL_REG1_SBYB |
MPL3115A2_CTRL_REG1_OS128 |
MPL3115A2_CTRL_REG1_BAR)
# Configure MPL3115A2
self._bus.write_byte_data(
MPL3115A2_ADDRESS,
MPL3115A2_PT_DATA_CFG,
MPL3115A2_PT_DATA_CFG_TDEFE |
MPL3115A2_PT_DATA_CFG_PDEFE |
MPL3115A2_PT_DATA_CFG_DREM)
def poll(self):
sta = 0
while not (sta & MPL3115A2_REGISTER_STATUS_PDR):
sta = self._bus.read_byte_data(MPL3115A2_ADDRESS, MPL3115A2_REGISTER_STATUS)
def get_altitude(self):
# print "Reading Altitude Data..."
self._bus.write_byte_data(
MPL3115A2_ADDRESS,
MPL3115A2_CTRL_REG1,
MPL3115A2_CTRL_REG1_SBYB |
MPL3115A2_CTRL_REG1_OS128 |
MPL3115A2_CTRL_REG1_ALT) # change to altimeter mode
self.poll()
msb, csb, lsb = self._bus.read_i2c_block_data(MPL3115A2_ADDRESS, MPL3115A2_REGISTER_PRESSURE_MSB, 3)
# print msb, csb, lsb
alt = float((((msb << 24) | (csb << 16) | lsb) * 10) / 65536)
# correct sign
if alt > (1 << 15):
alt -= 1 << 16
return alt
def get_pressure(self):
# print "Reading Pressure Data..."
self._bus.write_byte_data(
MPL3115A2_ADDRESS,
MPL3115A2_CTRL_REG1,
MPL3115A2_CTRL_REG1_SBYB |
MPL3115A2_CTRL_REG1_OS128 |
MPL3115A2_CTRL_REG1_BAR) # change to barometer mode
self.poll()
msb, csb, lsb = self._bus.read_i2c_block_data(MPL3115A2_ADDRESS, MPL3115A2_REGISTER_PRESSURE_MSB, 3)
# print msb, csb, lsb
return ((msb << 16) | (csb << 8) | lsb) / 64.
def calibrate(self):
# print "Calibrating..."
p = 0
t = 0
a = 0
calibration_rounds = 5
for _i in np.arange(0, calibration_rounds, 1):
p += self.get_pressure()
t += self.get_temperature()
a += self.get_altitude()
print("MPL3115A2 Calibration Round: {0} of {1}".format((_i+1), calibration_rounds))
pa = int((p / 10) / 2)
ta = (t / 10)
aa = (a / 10)
self._bus.write_i2c_block_data(MPL3115A2_ADDRESS, MPL3115A2_BAR_IN_MSB, [pa >> 8 & 0xff, pa & 0xff])
return [pa, ta, aa]
def get_temperature(self):
# print "Reading Temperature Data..."
self._bus.write_byte_data(
MPL3115A2_ADDRESS,
MPL3115A2_CTRL_REG1,
#.........这里部分代码省略.........
示例13: channel
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import write_i2c_block_data [as 别名]
class MPL115A2:
# select the SMBus channel (depends on RaspberryPI model)
bus = SMBus(0)
# the I2C address of the MPL115A2 sensor
# default is 0x60
MPL115A2_ADDRESS = (0x60)
# the register addresses of the MPL115A2 sensor
MPL115A2_REGISTER_PRESSURE_MSB = (0x00)
MPL115A2_REGISTER_PRESSURE_LSB = (0x01)
MPL115A2_REGISTER_TEMP_MSB = (0x02)
MPL115A2_REGISTER_TEMP_LSB = (0x03)
MPL115A2_REGISTER_A0_COEFF_MSB = (0x04)
MPL115A2_REGISTER_A0_COEFF_LSB = (0x05)
MPL115A2_REGISTER_B1_COEFF_MSB = (0x06)
MPL115A2_REGISTER_B1_COEFF_LSB = (0x07)
MPL115A2_REGISTER_B2_COEFF_MSB = (0x08)
MPL115A2_REGISTER_B2_COEFF_LSB = (0x09)
MPL115A2_REGISTER_C12_COEFF_MSB = (0x0A)
MPL115A2_REGISTER_C12_COEFF_LSB = (0x0B)
MPL115A2_REGISTER_STARTCONVERSION = (0x12)
# some private variables
a0_MSB = -1
a0_LSB = -1
b1_MSB = -1
b1_LSB = -1
b2_MSB = -1
b2_LSB = -1
c12_MSB = -1
c12_LSB = -1
_mpl115a2_a0 = -1
_mpl115a2_b1 = -1
_mpl115a2_b2 = -1
_mpl115a2_c12 = -1
pressure_MSB = -1
pressure_LSB = -1
temp_MSB = -1
temp_LSB = -1
temperature = -1
pressure = -1
def __init__(self, address=0x60, smbus=0, debug=True):
self.bus = SMBus(smbus)
self.MPL115A2_ADDRESS = address
self.debug = debug
# one time read factory calibrated coefficients from sensor
# Read the calibration data
self.read_coefficients()
# pass
# initiate conversion inside the sensor before metrics reading
def start_convert(self):
# send conversion command needed for pressure reading
self.bus.write_i2c_block_data(
self.MPL115A2_ADDRESS,
self.MPL115A2_REGISTER_STARTCONVERSION,
[0x12])
#
# sleep until the conversion is certainly completed
time.sleep(0.3)
def read_raw_data(self):
# prepare sensor for reading
self.start_convert()
# read pressure AGC units
self.pressure_MSB = self.bus.read_byte_data(
self.MPL115A2_ADDRESS,
self.MPL115A2_REGISTER_PRESSURE_MSB)
self.pressure_LSB = self.bus.read_byte_data(
self.MPL115A2_ADDRESS,
self.MPL115A2_REGISTER_PRESSURE_LSB)
# read raw temperature AGC units
self.temp_MSB = self.bus.read_byte_data(
self.MPL115A2_ADDRESS,
self.MPL115A2_REGISTER_TEMP_MSB + 0)
self.temp_LSB = self.bus.read_byte_data(
self.MPL115A2_ADDRESS,
self.MPL115A2_REGISTER_TEMP_LSB + 0)
# build
self.temperature = (self.temp_MSB << 8 | self.temp_LSB) >> 6
self.pressure = (self.pressure_MSB << 8 | self.pressure_LSB) >> 6
self.debug_output(" Raw temperature: " + str(self.temperature))
self.debug_output(" Raw pressure: " + str(self.pressure))
def read_raw_temperature(self):
# read raw temperature AGC units
self.temp_MSB = self.bus.read_byte_data(
self.MPL115A2_ADDRESS,
#.........这里部分代码省略.........
示例14: __init__
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import write_i2c_block_data [as 别名]
#.........这里部分代码省略.........
self._gpio_stby = gpio_stby
self._bus = SMBus(i2cbus)
sleep(0.5)
GPIO.setmode(GPIO.BCM if gpio_mode_bcm else GPIO.BOARD)
GPIO.setup(self._gpio_en, GPIO.OUT, GPIO.LOW)
GPIO.setup(self._gpio_stby, GPIO.OUT, GPIO.LOW)
self._state = {
"power": False,
"mute": True
}
self.DSP = DSP(self)
self.TUNER = TUNER(self)
# init GPIOs
self.power(False)
self.mute(True)
# end of method __init__
#*
#* Destructor
#*
def __del__(self):
self.power(False)
GPIO.cleanup()
# end of method __del__
#*
#* Turns on-board voltage regulators on or off
#* @param bool on - True/False for setting the power state, None to return current state only
#* @return bool - if the voltage regulators are on or off (software only)
#*
def power(self, on = None):
if on != None:
old_state = self._state["power"]
self._state["power"] = bool(on)
if not self._state["power"]:
self.mute(True)
self.DSP.beforePowerOff()
self.TUNER.beforePowerOff()
sleep(0.2)
GPIO.output(self._gpio_en, self._state["power"])
if not old_state and self._state["power"]:
sleep(0.5)
self.DSP.afterPowerOn()
self.TUNER.afterPowerOn()
return self._state["power"]
# end of method power
#*
#* Resets board by turning it off and then on after 2 seconds
#*
def reset(self):
self.power(False)
sleep(2)
self.power(True)
# end of method reset
#*
#* Enables or disables amplifier stand-by mode
#* @param bool on - True/False for setting the mute, None to return current state only
#* @return bool - if the amplifier is muted or not (software only)
#*
def mute(self, on = None):
if on != None:
on = bool(on)
if self._state["power"] or on:
self._state["mute"] = on
GPIO.output(self._gpio_stby, not self._state["mute"])
return self._state["mute"]
# end of method mute
#*
#* Send data over I2C if the Board is powered on
#* @param int address - address byte
#* @param tuple/list data - data bytes to be sent
#*
def _i2c_write(self, address, data):
if address < 0 or len(data) < 1:
return
if not self._state["power"]:# send data to board but only if it is powered
return
if len(data) > 1:
self._bus.write_i2c_block_data(address, data[0], data[1:])
else:
self._bus.write_byte(address, data[0])
示例15: ADS1x15
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import write_i2c_block_data [as 别名]
#.........这里部分代码省略.........
self.__ADS1015_REG_CONFIG_MODE_SINGLE
# Set sample per seconds, defaults to 250sps
# If sps is in the dictionary (defined in init) it returns the value of the constant
# othewise it returns the value for 250sps. This saves a lot of if/elif/else code!
if (self.ic == self.__IC_ADS1015):
config |= self.spsADS1015.setdefault(sps, self.__ADS1015_REG_CONFIG_DR_1600SPS)
else:
if ( (sps not in self.spsADS1115) & self.debug):
print "ADS1x15: Invalid pga specified: %d, using 6144mV" % sps
config |= self.spsADS1115.setdefault(sps, self.__ADS1115_REG_CONFIG_DR_250SPS)
# Set PGA/voltage range, defaults to +-6.144V
if ( (pga not in self.pgaADS1x15) & self.debug):
print "ADS1x15: Invalid pga specified: %d, using 6144mV" % sps
config |= self.pgaADS1x15.setdefault(pga, self.__ADS1015_REG_CONFIG_PGA_6_144V)
self.pga = pga
# Set the channel to be converted
if channel == 3:
config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_3
elif channel == 2:
config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_2
elif channel == 1:
config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_1
else:
config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_0
# Set 'start single-conversion' bit
config |= self.__ADS1015_REG_CONFIG_OS_SINGLE
# Write config register to the ADC
bytes = [(config >> 8) & 0xFF, config & 0xFF]
self.__i2c.write_i2c_block_data(self.__slave, self.__ADS1015_REG_POINTER_CONFIG, bytes)
# Wait for the ADC conversion to complete
# The minimum delay depends on the sps: delay >= 1/sps
# We add 0.1ms to be sure
delay = 1.0/sps+0.0001
time.sleep(delay)
# Read the conversion results
result = self.__i2c.read_i2c_block_data(self.__slave, self.__ADS1015_REG_POINTER_CONVERT, 2)
if (self.ic == self.__IC_ADS1015):
# Shift right 4 bits for the 12-bit ADS1015 and convert to mV
return ( ((result[0] << 8) | (result[1] & 0xFF)) >> 4 )*pga/2048.0
else:
# Return a mV value for the ADS1115
# (Take signed values into account as well)
val = (result[0] << 8) | (result[1])
if val > 0x7FFF:
return (val - 0xFFFF)*pga/32768.0
else:
return ( (result[0] << 8) | (result[1]) )*pga/32768.0
def readADCDifferential(self, chP=0, chN=1, pga=6144, sps=250):
"""Gets a differential ADC reading from channels chP and chN in mV.
The sample rate for this mode (single-shot) can be used to lower the noise
(low sps) or to lower the power consumption (high sps) by duty cycling,
see data sheet page 14 for more info.
The pga must be given in mV, see page 13 for the supported values."""
# Disable comparator, Non-latching, Alert/Rdy active low
# traditional comparator, single-shot mode
config = self.__ADS1015_REG_CONFIG_CQUE_NONE | \
self.__ADS1015_REG_CONFIG_CLAT_NONLAT | \