本文整理汇总了Python中smbus.SMBus.read_word_data方法的典型用法代码示例。如果您正苦于以下问题:Python SMBus.read_word_data方法的具体用法?Python SMBus.read_word_data怎么用?Python SMBus.read_word_data使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类smbus.SMBus
的用法示例。
在下文中一共展示了SMBus.read_word_data方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_temp
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import read_word_data [as 别名]
def get_temp():
# zlecenie konwersji
i2c_bus = SMBus(1)
i2c_bus.write_byte_data(Register.LIGHT2_ADDRESS, 10, 1)
sleep(1)
cel = i2c_bus.read_word_data(0x20, 5)
cel = cel >> 8
return cel
示例2: MTSMBus
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import read_word_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)
示例3: Device
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import read_word_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
示例4: templogger
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import read_word_data [as 别名]
#.........这里部分代码省略.........
def readPressure(self):
# Get raw temperature and pressure
ut = self.readRawTemp()
up = self.readRawPressure()
# Convert to actual compensated and calibrated pressure (see Datasheet)
x1 = ((ut - self._cal_AC6) * self._cal_AC5) >> 15
x2 = (self._cal_MC << 11) / (x1 + self._cal_MD)
b5 = x1 + x2
b6 = b5 - 4000
x1 = (self._cal_B2 * (b6 * b6) >> 12) >> 11
x2 = (self._cal_AC2 * b6) >> 11
x3 = x1 + x2
b3 = (((self._cal_AC1 * 4 + x3) << 3) + 2) / 4
x1 = (self._cal_AC3 * b6) >> 13
x2 = (self._cal_B1 * ((b6 * b6) >> 12)) >> 16
x3 = ((x1 + x2) + 2) >> 2
b4 = (self._cal_AC4 * (x3 + 32768)) >> 15
b7 = (up - b3) * (50000 >> 3)
if (b7 < 0x80000000):
p = (b7 * 2) / b4
else:
p = (b7 / b4) * 2
x1 = (p >> 8) * (p >> 8)
x1 = (x1 * 3038) >> 16
x2 = (-7357 * p) >> 16
p = p + ((x1 + x2 + 3791) >> 4)
return p
def readLM75Temperature(self):
# Measure temperature
temp = self.i2c1.read_word_data(self.lm75addr,0)
# Swap lower and higher byte
temp = (((temp & 0xff) << 8)|((temp >> 8) & 0xff))
value = temp >> 5
# Make signed integer
if (temp & 0x8000):
# one's complement
value = (~value & 0x1FF)
# two's complement
value = value - 1
# significance: means negative temp
value = -value
value = value / 8.0
return value
def readBH1750Light(self):
# Measure light
luxtmp = self.i2c1.read_word_data(self.bh1750, 0x10)
# Convert to actual lux (see Datasheet)
lux = (((luxtmp >> 8) & 0xff) | ((luxtmp & 0xff) << 8))/1.2
return lux
def measure(self):
thisdate = datetime.datetime.utcnow()
nu = datetime.datetime.utcnow()
print(thisdate)
value = self.readLM75Temperature()
#self.publish(self.tempds, value, nu)
self.db.execute(
'INSERT INTO temp_series(date, event, value, detail) VALUES(?,?,?,?)',
(
thisdate,
"Temperature",
示例5: sensirion
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import read_word_data [as 别名]
class SHT21 :
RHmeasure_noHold = 0xF5
Tmeasure_noHold = 0xF3
RHmeasure_Hold = 0xE5
Tmeasure_Hold = 0xE3
Soft_Reset = 0xFE
Write_Reg = 0xE6
Read_Reg = 0xE7
##############################################################################
## Experimental register found by looking for each one individually ##
## with a 10 seconds wait between each try. CheckCRC says true for all. ##
RH_Reg = 0x05 ##
T_Reg = 0x03 ##
## read_reg? 0x06 ##
## read_reg 0x07 ##
## unknown 0x09 result was 6,0,90(constant over time) ##
## unknown 0x0F result was 2,68,32(constant over time) ##
## serial number? 0x1A periodic on 64 bits? ##
## result was [25, 203, 218, 223, 71, 170, 137, 242, 217, 140, 232 ##
## , 120, 231, 86, 128, 122, 7, 151, 248, 59, 252, 255, ##
## 232, 120, 54, 99, 129, 75, 30, 92, 80, 126] ##
## serial number? 0x1B same as 0x1A with random shift ##
## T_reg? 0xE3 result was 103,88,60(made a new measure?) ##
## RH_reg? 0xE5 result was 83,206,146(new measure?) ##
## read_reg 0xE6 result was 58,30 ##
## read_reg 0xE7 result was 58,30 ##
## unknown 0xE9 result was 6,0,90 ##
## unknown 0xEF result was 2,68,32 ##
## serial number 0xFA same as 1A, check sensirion(says 64 bits ID)##
## serial number? 0xFB same as 1B ##
## device ID? 0xFF check i2c full specs, results seems random ##
############################1#################################################
class CRCError(Exception):
pass
def __init__(self, addr, busnum = 1) :
self.address = addr
self.bus = SMBus(busnum)
#self.bus.open(busnum)
self.Reset()
#reg = self.ReadReg()
reg = 0
if (reg & 0x80) and (reg & 0x01):
self.RH_res = 11
self.T_res = 11
elif (reg & 0x80) and not(reg & 0x01):
self.RH_res = 10
self.T_res = 13
elif not(reg & 0x80) and not(reg & 0x01):
self.RH_res = 12
self.T_res = 14
else:
self.RH_res = 8
self.T_res = 12
def getRH(self):
self.bus.write_byte(self.address, self.RHmeasure_noHold)
time.sleep(0.1)
RH = self.bus.read_i2c_block_data(self.address, self.RH_Reg, 3)
#print RH
if self.CheckCRC(RH):
self.RHum = RH
RH[1] &= ~0x03 #reset 2 status bits(LSB)
return -6+125.*(RH[0]*256+RH[1])/65536.
else:
#print 'CRC checksum failed, data was corrupted(RH reading)'
#return -1
raise self.CRCError
def getT(self):
self.bus.write_byte(self.address, self.Tmeasure_noHold)
time.sleep(0.1)
T = self.bus.read_i2c_block_data(self.address, self.T_Reg, 3)
#print T
if self.CheckCRC(T):
self.Temp = T
T[1] &= ~0x03 #reset 2 status bits(LSB)
return -46.85+175.72*(T[0]*256+T[1])/65536.
else:
#print 'CRC checksum failed, data was corrupted(temp reading)'
#return -1
raise self.CRCError
def Reset(self):
self.bus.write_byte(self.address, self.Soft_Reset)
time.sleep(0.02) #must wait 15ms
def ReadReg(self):
reg = self.bus.read_word_data(self.address, self.Read_Reg)
crc = [ reg & 0xFF, (reg & 0xFF00) >> 8]
if self.CheckCRC(crc):
return reg & 0xFF
else:
#print 'Error : CRC not matching !'
#return 0
raise self.CRCError
def WriteReg(self, val):
#.........这里部分代码省略.........
示例6: sleep
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import read_word_data [as 别名]
p.ChangeFrequency(note[0])
sleep(note[1])
p.stop()
p.ChangeFrequency(N_BOUNCE)
for led in LEDS: gpio.setup(led, gpio.OUT)
oldBugger = WIDTH * HEIGHT * [None]
oldTime = time()
counter = 0
sorry = True
while 1:
newTime = time()
counter += newTime - oldTime
if newTime - sfxStartTime > sfxLength:
p.stop()
adc.write_byte(33, 128)
knob = adc.read_word_data(33, 0)
knob = ((knob & 15) << 8 | knob >> 8) - 683
if knob < 0: knob = 0
elif knob > 2730: knob = 2730
Player0Bat = HEIGHT - int(round(knob * (HEIGHT - Player0Height) / 2731.)) - Player0Height
if sorry:
knob = adc.read_byte_data(36,0) - 9
if knob < 0: knob = 0
elif knob > 220: knob = 220
Player1Bat = HEIGHT - int(round(knob * (HEIGHT - Player1Height) / 220.)) - Player1Height
gpio.output(17, 1)
gpio.output(17, 0)
sorry = not sorry
if Player0SizeCounter < 15: Player0SizeCounter += newTime - oldTime
else: Player0Height = 3
if Player1SizeCounter < 15: Player1SizeCounter += newTime - oldTime
示例7: parse
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import read_word_data [as 别名]
def parse(t):
# 9 bits of resolution stored in 2 bytes
r = t >> 7
# MSB set?
if t & 0x8000:
# one's complement
r = ~r & 0x1FF
# two's complement
r = r - 1
# significance: means negative temp
r = -r
r = r / 2.0
return r
def ctof(t):
return ((9.0 / 5.0) * parse(t)) + 32.0
while True:
temp = i2c1.read_word_data(addr, 0)
tempA = temp & 0xFF
tempB = (temp >> 8) & 0xFF
temp = (tempA << 8) | tempB
print "read: %04x = %.1f C (%.1f F)" % (temp, parse(temp), ctof(temp))
time.sleep(0.5)
示例8: __init__
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import read_word_data [as 别名]
class SRF02:
def __init__(self):
self._i2c = SMBus(1)
self._i2c_address = SRF02_I2C_ADDRESS
self._waiting_for_echo = False
yesterday = datetime.now() - timedelta(1)
self._time_last_burst = yesterday
# The last distance measurement
self.distance = None # meters
# On power up, the detection threshold is set to 28cm (11")
self.mindistance = 0.28 # meters
# This is mostly for debugging and testing
self.num_bursts_sent = 0
# check that the sensor is present - read the version
self.version = self._read_version()
log.info("SRF-02 Ultrasonic Sensor initialized. Version: %d" % self.version)
# we want to check how often we get exceptions
self.error_counter = 0
# Should be called in some sensor loop, maybe at 100Hz. Is fast.
# Will trigger an ultrasonic burst or check if we received an echo.
# I we have a measurement, it is returned in meters.
def update(self):
distance = None
now = datetime.now()
time_since_last_burst = (now - self._time_last_burst).total_seconds()
# log.debug("time since last burst: {}".format(time_since_last_burst))
if self._waiting_for_echo:
# make sure we wait at least some amount of time before we read
if time_since_last_burst > SRF02_MIN_TIME_BETWEEN_BURST_READ:
# check if we have an echo
distance = self._read_echo()
# Fallback if we don't get an echo, just stop waiting
# from the data sheet:
# The SRF02 will always be ready 70mS after initiating the ranging.
if distance is None and time_since_last_burst > SRF02_MAX_WAIT_TIME:
log.warn("Fallback! Waited longer than 70ms!")
self._waiting_for_echo = False
if (not self._waiting_for_echo) and time_since_last_burst > SRF02_MIN_TIME_BETWEEN_BURSTS:
self._send_burst()
expected_error = self._calc_expected_error(distance)
return distance, expected_error
def _send_burst(self):
self._i2c.write_byte_data(self._i2c_address, 0, 0x51)
self._waiting_for_echo = True
self._time_last_burst = datetime.now()
self.num_bursts_sent += 1
log.debug("Burst sent.")
def _read_echo(self):
# it must be possible to read all of these data in 1 i2c transaction
# buf[0] software version. If this is 255, then the ping has not yet returned
# buf[1] unused
# buf[2] high byte range
# buf[3] low byte range
# buf[4] high byte minimum auto tuned range
# buf[5] low byte minimum auto tuned range
# We use the version information to detect if the result is there yet.
# 255 is a dummy version for the case that no echo has been received yet. For me, the real version is "6".
if self._read_version() == 255:
log.debug("Version is 255")
return None
self.distance = self._i2c.read_word_data(self._i2c_address, 2) / 255 / 100
self.mindistance = self._i2c.read_word_data(self._i2c_address, 4) / 255 / 100
# A value of 0 indicates that no objects were detected. We prefer None to represent this.
if self.distance == 0:
self.distance = None
self._waiting_for_echo = False
log.debug("echo received! distance is: {}".format(self.distance))
return self.distance
# The version can be read from register 0.
# Reading it has no real value for us, but we can use it to determine if a measurement is finished or not.
def _read_version(self):
try:
return self._i2c.read_byte_data(self._i2c_address, 0)
# 255 means that the unit is still measuring the distance
except IOError:
#.........这里部分代码省略.........
示例9: MLX90614_IR_sensor
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import read_word_data [as 别名]
class MLX90614_IR_sensor():
'''This class will read the IR temperatue values from the sensor'''
def __init__(self, address):
'''Initalizing all variables
'''
#address working at
self.address = address
#note that the default slave address is 0x00
#TODO: how to detect several different addresses at once
#self.address = 0x5a
#Objec temperature address
self.tobj_address = 0x27 #0x27
#ambien temperature address
self.tamb_address = 0x26 #0x26
#smbus command setup
self.bus = SMBus(1)
#inital ambient and object temperatures
self.init_tamb_value = 0.0
self.init_tobj_value = 0.0
#inital tamb and tobj values converted to Celsius
self.tamb_ans= 0.0
self.tobj_ans= 0.0
#ambient temperature
self.tamb_num = 0.0
#object temperature
self.tobj_num = 0.0
self.tobj_percent_limit_up=0.0
self.tobj_percent_limit_down=0.0
self.tamb_percent_limit_up=0.0
self.tamb_percent_limit_down=0.0
#instantiate the config file and extract the dict
#opening the config file
self.config = config.config.Config()
#reading the config file
#self.config.readconfig()
#extract the slice and slice values
#print self.config.dict
#dict length for data analysis
self.length = int(self.config.dict['length'])
#slice length of data analysis
self.slice = int(self.config.dict['slice'])
#importing the control_variable() class to obtain the jump and limit values
self.control_class = mlx.control_variable.Control_Variable()
self.control_class.run()
self.tobj_jump_value = 0.0
self.tamb_jump_value = 0.0
self.cycle = 0
self.counter = 0
self.tamb_data_analysis_list = []
self.tobj_data_analysis_list = []
self.tobj_data_analysis_result = []
self.tamb_data_analysis_result = []
#this is the record_list which is the varible passed to the gui
#note that we are initalizing all variables with 0 are the six variables are there
#the appended list data is being stored to the log files, the gui will only show a subaspect of the data
self.record_list = [0,0,0,0,0,0]
self.record_dict = {self.address: []} #, 'cycle':self.cycle }
def read(self):
'''getting the values from the IR device sensor'''
self.init_tobj_value = self.bus.read_word_data(self.address, self.tobj_address)
#sleep for 200 ms the time for the sensor is at least 144 ms
time.sleep(0.2)
self.init_tamb_value = self.bus.read_word_data(self.address, self.tamb_address)
#sleep for 200 ms the timer for the sensor is at least 144 ms
time.sleep(0.2)
def object_temp_analysis(self):
'''this function converts the object temperature from kelvin to celsius values'''
#converting values from long bits into degrees celsius
#using fomula in sensor datasheet manual
#pg ?????
#convert temperatures from kelvin to celsius
tobj_ans = ( self.init_tobj_value*0.02 ) - 273.15
#print tobj_ans
self.tobj_ans = tobj_ans
#mylog2.debug('Tobj: ' + repr(tobj_ans) )
#calculate jump value
jump_value = tobj_ans - self.tobj_num #- tobj_ans
#save calculated jump value to self value
#.........这里部分代码省略.........
示例10: I2CDevice
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import read_word_data [as 别名]
#.........这里部分代码省略.........
self._bus.write_word_data(self._address, register, value)
self._logger.debug(
'Wrote to register pair {:#x}, {:#x} value {:#x} '.format(
register, register + 1, value
)
)
def read(self):
"""
Read the device base address and return a 8-bit value.
"""
result = self._bus.read_byte(self._address) & 0xFF
self._logger.debug(
'Read value {:#x}'.format(result)
)
return result
def register_read_u8(self, register):
"""
Read the specified 8-bit register and return a 8-bit value.
"""
assert bound_bits(register, 8)
result = self._bus.read_byte_data(self._address, register) & 0xFF
self._logger.debug(
'Read from register {:#x} returns {:#x}'.format(register, result)
)
return result
def register_read_s8(self, register):
"""
Read the specified 8-bit register and return a signed 7-bit value.
"""
result = self.register_read_u8(register)
if result > 127:
result -= 256
self._logger.debug('... as signed: {:#x}'.format(result))
return result
def register_read_u16(self, register, little_endian=True):
"""
Read the specified 8-bit register and return a 16-bit value with the
specified endianness.
Default is little endian, or least significant byte first.
"""
assert bound_bits(register, 8)
result = self._bus.read_word_data(self._address, register) & 0xFFFF
self._logger.debug(
'Read from register pair {:#x}, {:#x} value {:#x} '.format(
register, register + 1, result
)
)
# Swap bytes if using big endian because read_word_data assumes little
# endian on ARM (little endian) systems.
if not little_endian:
result = ((result << 8) & 0xFF00) + (result >> 8)
self._logger.debug('... as big endian: {:#x}'.format(result))
return result
def register_read_s16(self, register, little_endian=True):
"""
Read the specified 8-bit register and return a signed 15-bit value
with the specified endianness.
Default is little endian, or least significant byte first.
"""
result = self.register_read_u16(register, little_endian)
if result > 32767:
result -= 65536
self._logger.debug('... as signed: {:#x}'.format(result))
return result
def register_read_u16le(self, register):
"""
Same as register_read_u16 with endianness set to little endian.
"""
return self.register_read_u16(register, little_endian=True)
def register_read_u16be(self, register):
"""
Same as register_read_u16 with endianness set to big endian.
"""
return self.register_read_u16(register, little_endian=False)
def register_read_s16le(self, register):
"""
Same as register_read_s16 with endianness set to little endian.
"""
return self.register_read_s16(register, little_endian=True)
def register_read_s16be(self, register):
"""
Same as register_read_s16 with endianness set to big endian.
"""
return self.register_read_s16(register, little_endian=False)
示例11: weather
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import read_word_data [as 别名]
class weather():
_cal_AC1 = 0
_cal_AC2 = 0
_cal_AC3 = 0
_cal_AC4 = 0
_cal_AC5 = 0
_cal_AC6 = 0
_cal_B1 = 0
_cal_B2 = 0
_cal_MB = 0
_cal_MC = 0
_cal_MD = 0
bmp180 = 0
bh1750 = 0
lm75addr = 0
i2c1 = 0
db = 0
api = 0
feed = 0
tempds = 0
lightds = 0
pressds = 0
def __init__(self):
self.lm75addr = 0x4f
self.bmp180 = 0x77
self.bh1750 = 0x23
self.i2c1 = SMBus(1)
self.calibration()
def calibration(self):
self._cal_AC1 = self.read_16bit_regs(self.bmp180, 0xaa)
self._cal_AC2 = self.read_16bit_regs(self.bmp180, 0xac)
self._cal_AC3 = self.read_16bit_regs(self.bmp180, 0xae)
self._cal_AC4 = self.read_16bit_regu(self.bmp180, 0xb0)
self._cal_AC5 = self.read_16bit_regu(self.bmp180, 0xb2)
self._cal_AC6 = self.read_16bit_regu(self.bmp180, 0xb4)
self._cal_B1 = self.read_16bit_regs(self.bmp180, 0xb6)
self._cal_B2 = self.read_16bit_regs(self.bmp180, 0xb8)
self._cal_MB = self.read_16bit_regs(self.bmp180, 0xba)
self._cal_MC = self.read_16bit_regs(self.bmp180, 0xbc)
self._cal_MD = self.read_16bit_regs(self.bmp180, 0xbe)
def readRawTemp(self):
self.i2c1.write_byte_data(self.bmp180, 0xf4, 0x2e)
time.sleep(0.005)
raw = self.read_16bit_regu(self.bmp180, 0xf6)
return raw
def readTemperature(self):
ut = self.readRawTemp()
x1 = ((ut - self._cal_AC6) * self._cal_AC5) >> 15
x2 = (self._cal_MC << 11) / (x1 + self._cal_MD)
b5 = x1 + x2
temp = ((b5 + 8) >> 4)/10.0
return temp
def readRawPressure(self):
self.i2c1.write_byte_data(self.bmp180, 0xf4, 0xf4) #Read ultra high resolution
time.sleep(0.026)
msb = self.i2c1.read_byte_data(self.bmp180, 0xf6)
lsb = self.i2c1.read_byte_data(self.bmp180, 0xf7)
xlsb = self.i2c1.read_byte_data(self.bmp180, 0xf8)
raw = (msb << 16) + (lsb << 8) + (xlsb) >> 5
return raw
def readPressure(self):
# Get raw temperature and pressure
ut = self.readRawTemp()
up = self.readRawPressure()
# Convert to actual compensated and calibrated pressure (see Datasheet)
x1 = ((ut - self._cal_AC6) * self._cal_AC5) >> 15
x2 = (self._cal_MC << 11) / (x1 + self._cal_MD)
b5 = x1 + x2
b6 = b5 - 4000
x1 = (self._cal_B2 * (b6 * b6) >> 12) >> 11
x2 = (self._cal_AC2 * b6) >> 11
x3 = x1 + x2
b3 = (((self._cal_AC1 * 4 + x3) << 3) + 2) / 4
x1 = (self._cal_AC3 * b6) >> 13
x2 = (self._cal_B1 * ((b6 * b6) >> 12)) >> 16
x3 = ((x1 + x2) + 2) >> 2
b4 = (self._cal_AC4 * (x3 + 32768)) >> 15
b7 = (up - b3) * (50000 >> 3)
if (b7 < 0x80000000):
p = (b7 * 2) / b4
else:
p = (b7 / b4) * 2
x1 = (p >> 8) * (p >> 8)
x1 = (x1 * 3038) >> 16
x2 = (-7357 * p) >> 16
p = p + ((x1 + x2 + 3791) >> 4)
return p
def readLM75Temperature(self):
# Measure temperature
temp = self.i2c1.read_word_data(self.lm75addr,0)
#.........这里部分代码省略.........
示例12: SMBus
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import read_word_data [as 别名]
from smbus import SMBus
from time import sleep
i2c = SMBus(1)
while True:
try:
i2c.write_byte(0x70, 0x51)
sleep(0.3)
datin = i2c.read_word_data(0x70, 0xe1)
print ((datin >> 8) & 0x00ff) | ((datin << 8) & 0xff00), 'cm'
except:
print err
示例13: it
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import read_word_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
#.........这里部分代码省略.........