本文整理汇总了Python中smbus.SMBus.read_byte方法的典型用法代码示例。如果您正苦于以下问题:Python SMBus.read_byte方法的具体用法?Python SMBus.read_byte怎么用?Python SMBus.read_byte使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类smbus.SMBus
的用法示例。
在下文中一共展示了SMBus.read_byte方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: PCF8574
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import read_byte [as 别名]
class PCF8574(object):
def __init__(self, bus_id, address):
super().__init__()
self.__bus = SMBus(bus_id)
self.__address = address
self.__value = self.__getRealValue()
@property
def value(self):
return self.__value
@value.setter
def value(self, value):
self.__bus.write_byte(self.__address,
(~value) & 0xff
)
self.__value = value
def flipBits(self, changeBits):
self.value ^= changeBits
def __getRealValue(self):
value = self.__bus.read_byte(self.__address)
return (~value) & 0xff
示例2: __init__
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import read_byte [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
示例3: MTSMBus
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import read_byte [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)
示例4: __init__
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import read_byte [as 别名]
class i2cDevice:
def __init__(self, bus_number):
self.BC_addr = 0x25
self.bus = SMBus(bus_number)
def read_register(self, address):
self.bus.write_byte(self.BC_addr, address)
time.sleep(0.02)
data = struct.pack('B', self.bus.read_byte(self.BC_addr))
return data
def write_register(self, address, data):
self.bus.write_byte_data(self.BC_addr, address, data)
time.sleep(0.02)
示例5: Device
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import read_byte [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
示例6: get
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import read_byte [as 别名]
def get(self):
lStatus = "ok"
lCommand = ""
lValue = ""
lArgs = self.__mParser.parse_args()
lBusId = int(lArgs['bus_id'], 0)
lBus = SMBus(lBusId)
lAddress = int(lArgs['address'], 0)
try:
if lArgs['cmd'] is None:
lValue = lBus.read_byte(lAddress)
else:
lCommand = int(lArgs['cmd'], 0)
lValue = lBus.read_byte_data(lAddress, lCommand)
except IOError, pExc:
lStatus = "Error reading from bus: " + str(pExc)
示例7: getTemp
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import read_byte [as 别名]
def getTemp():
rdis_addr = r_server.hget("config.sensor.1", "Address")
address = int(rdis_addr, 16)
bus = SMBus(1)
raw_temp = bus.read_byte(address)
vorkomma = raw_temp & 0xFF
nachkomma = raw_temp >> 15
# ist Wert positiv oder negativ
if (vorkomma & 0x80) != 0x80: # positiv
temp = vorkomma + nachkomma * 0.5
else: # negativ
vorkomma = -((~vorkomma & 0xFF) + 1)
temp = vorkomma + nachkomma * (0.5)
# print (temp)
r_server.hset("boat.temperature", "value", temp)
r_server.hset("boat.temperature", "time", vtime)
示例8: TemperatureSensor
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import read_byte [as 别名]
class TemperatureSensor(object):
def __init__(self):
log.debug("Initialising temperature/humidity sensor")
self.bus = SMBus(1)
self.address = 0x40
self.MEASURE_RELATIVE_TEMPERATURE = 0xE3
self.MEASURE_RELATIVE_HUMIDITY = 0xE5
self.READ_FIRMWARE_VERSION = '\x84\xb8'
def read_firmware_version(self):
self.bus.write_byte(self.address, 0x84)
self.bus.write_byte(self.address, 0xB8)
response = self.bus.read_byte(self.address)
print 'firmware version:', response
# response = self.bus.read_byte_data(self.address,
# 0xB8)
# print 'firmware version:', response
return response
def read_temperature(self):
# Return dummy data for now
# return 20. + random.random()
response = self.bus.read_byte_data(self.address,
self.MEASURE_RELATIVE_TEMPERATURE)
print 'temperature:', response
return response
def read_humidity(self):
# Return dummy data for now
# return random.randint(40, 90)
response = self.bus.read_byte_data(self.address,
self.MEASURE_RELATIVE_HUMIDITY)
print 'humidity:', response
return response
示例9: I2CDevice
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import read_byte [as 别名]
class I2CDevice(object):
"""
Class for communicating with an I2C device.
Allows reading and writing 8-bit, 16-bit, and byte array values to
registers on the device.
It can handle signed, unsigned and endianness.
:var uint address: Assigned I2C address.
:var uint8 busid: Assigned IC2 bus identifier.
:param uint address: I2C address.
:param uint busid: IC2 bus identifier.
:param class i2c_class: Class implementing the I2C reading interface.
If None, smbus.SMBus will be used.
"""
def __init__(self, busnum, address, i2c_class=None):
self._busnum = busnum
self._address = address
if i2c_class is None:
from smbus import SMBus
self._bus = SMBus(busnum)
else:
self._bus = i2c_class(busnum)
self._logger = logging.getLogger(
'/dev/i2c-{}/{:#x}'.format(busnum, address)
)
def _debug(self):
self._logger.setLevel(logging.DEBUG)
self._logger.addHandler(logging.StreamHandler())
@property
def busnum(self):
return self._busnum
@property
def address(self):
return self._address
def write(self, value):
"""
Write the specified 8-bit value to the device base address.
"""
assert bound_bits(value, 8)
self._bus.write_byte(self._address, value)
self._logger.debug(
'Wrote value {:#x}'.format(value)
)
def register_write_u8(self, register, value):
"""
Write an 8-bit value to the specified 8-bit register.
"""
assert bound_bits(register, 8)
assert bound_bits(value, 8)
self._bus.write_byte_data(self._address, register, value)
self._logger.debug(
'Wrote to register {:#x} value {:#x}'.format(register, value)
)
def register_write_u16(self, register, value):
assert bound_bits(register, 8)
assert bound_bits(value, 16)
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
#.........这里部分代码省略.........
示例10: __init__
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import read_byte [as 别名]
class SHT21:
"""Class to read temperature and humidity from SHT21"""
## Control constants
_SOFTRESET = 0xFE
_SLAVE_ADDRESS = 0x40
_TRIGGER_TEMPERATURE_NO_HOLD = 0xF3
_TRIGGER_HUMIDITY_NO_HOLD = 0xF5
_STATUS_BITS_MASK = 0xFFFC
# Wait a bit more than recommended
_TEMPERATURE_WAIT_TIME = 0.086 # (datasheet: typ=66, max=85)
_HUMIDITY_WAIT_TIME = 0.030 # (datasheet: typ=22, max=29)
def __init__(self, device_number = 1):
"""Opens the i2c device (assuming that the kernel modules have been
loaded) & run soft reset. (user register leaved to default value)"""
self.bus = SMBus(device_number)
self.bus.write_byte(self._SLAVE_ADDRESS, self._SOFTRESET)
time.sleep(0.015)
if DEBUG:
print("SHT21 init done.")
def getTemperature(self):
"""Reads the temperature from the sensor. Not that this call blocks
for ~86ms to allow the sensor to return the data """
self.bus.write_byte(self._SLAVE_ADDRESS, self._TRIGGER_TEMPERATURE_NO_HOLD)
data = []
time.sleep(self._TEMPERATURE_WAIT_TIME)
data.append(self.bus.read_byte(self._SLAVE_ADDRESS))
data.append(self.bus.read_byte(self._SLAVE_ADDRESS))
Temperature = self._get_temperature_from_buffer(data)
if DEBUG:
print("Temp[C] = ", Temperature)
return Temperature
def getHumidity(self):
"""Reads the humidity from the sensor. Not that this call blocks
for ~30ms to allow the sensor to return the data"""
self.bus.write_byte(self._SLAVE_ADDRESS, self._TRIGGER_HUMIDITY_NO_HOLD)
data = []
time.sleep(self._HUMIDITY_WAIT_TIME)
data.append(self.bus.read_byte(self._SLAVE_ADDRESS))
data.append(self.bus.read_byte(self._SLAVE_ADDRESS))
Humidity = self._get_humidity_from_buffer(data)
if DEBUG:
print("Humidity[%] = ", Humidity)
return Humidity
@staticmethod
def _get_temperature_from_buffer(data):
"""This function reads the first two bytes of data and
returns the temperature in C by using the following function:
T = =46.82 + (172.72 * (ST/2^16))where ST is the value from the sensor """
unadjusted = ((data[0]) << 8) + (data[1])
unadjusted &= SHT21._STATUS_BITS_MASK # zero the status bits
unadjusted *= 175.72
unadjusted /= 1 << 16 # divide by 2^16
unadjusted -= 46.85
return unadjusted
@staticmethod
def _get_humidity_from_buffer(data):
"""This function reads the first two bytes of data and returns
the relative humidity in percent by using the following function:
RH = -6 + (125 * (SRH / 2 ^16)) where SRH is the value read from the sensor """
unadjusted = (data[0] << 8) + data[1]
unadjusted &= SHT21._STATUS_BITS_MASK # zero the status bits
unadjusted *= 125.0
unadjusted /= 1 << 16 # divide by 2^16
unadjusted -= 6
return unadjusted
@staticmethod
def _calculate_checksum(data, number_of_bytes):
"""5.7 CRC Checksum using the polynomial given in the datasheet"""
# CRC
POLYNOMIAL = 0x131 # //P(x)=x^8+x^5+x^4+1 = 100110001
crc = 0
# calculates 8-Bit checksum with given polynomial
for byteCtr in range(number_of_bytes):
crc ^= (data[byteCtr])
for bit in range(8, 0, -1):
if crc & 0x80:
crc = (crc << 1) ^ POLYNOMIAL
else:
crc = (crc << 1)
return crc
示例11: len
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import read_byte [as 别名]
import optparse
from smbus import SMBus
import time
#######################
# Get options
#######################
parser = optparse.OptionParser("usage: %prog [options] <decimal to write>")
#parser.add_option ('-a', dest='address', type='string',
# default = '70',
# help="Hex value of address of i2c device.")
options, args = parser.parse_args()
if len(args) != 1:
print "Please specify decimal integer to write via i2c"
sys.exit()
byteToWrite = int(args[0])
#######################
bus = SMBus(1)
address = 0x70
print bus.read_byte(address)
bus.write_byte(address, byteToWrite)
print bus.read_byte(address)
示例12: __init__
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import read_byte [as 别名]
class sgh_PCF8591P:
# Constructor
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 present 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 readADC(self, __chan = 0):
__checkedChan = self.__checkChannelNo(__chan)
self.__bus.write_byte(self.__addr, 0x40 | __checkedChan & 0x03) # mod my Max - says it more reliable
# self.__bus.write_byte(self.__addr, __checkedChan | self.__DACEnabled)
__reading = self.__bus.read_byte(self.__addr) # seems to need to throw away first reading
__reading = self.__bus.read_byte(self.__addr) # read A/D
return __reading
# Read all ADC channels
def readAllADC(self):
__readings = []
self.__bus.write_byte(self.__addr, 0x04 | self.__DACEnabled)
__reading = self.__bus.read_byte(self.__addr) # seems to need to throw away first reading
for i in range (4):
__readings.append(self.__bus.read_byte(self.__addr)) # read ADC
return __readings
# Set DAC value and enable output
def writeDAC(self, __val=0):
__checkedVal = self.__checkDACVal(__val)
self.__DACEnabled = 0x40
self.__bus.write_byte_data(self.__addr, self.__DACEnabled, __checkedVal)
# Enable DAC output
def enableDAC(self):
self.__DACEnabled = 0x40
self.__bus.write_byte(self.__addr, self.__DACEnabled)
# Disable DAC output
def disableDAC(self):
self.__DACEnabled = 0x00
self.__bus.write_byte(self.__addr, self.__DACEnabled)
# Check I2C address is within bounds
def __checkI2Caddress(self, __addr):
if type(__addr) is not int:
raise I2CaddressOutOfBoundsError
elif (__addr < 0):
raise I2CaddressOutOfBoundsError
elif (__addr > 127):
raise I2CaddressOutOfBoundsError
return __addr
# Check if ADC channel number is within bounds
def __checkChannelNo(self, __chan):
if type(__chan) is not int:
raise PCF8591PchannelOutOfBoundsError
elif (__chan < 0):
raise PCF8591PchannelOutOfBoundsError
elif (__chan > 3):
raise PCF8591PchannelOutOfBoundsError
return __chan
# Check if DAC output value is within bounds
def __checkDACVal(self, __val):
if type(__val) is not int:
raise PCF8591PDACvalueOutOfBoundsError
elif (__val < 0):
raise PCF8591PDACvalueOutOfBoundsError
elif (__val > 255):
raise PCF8591PDACvalueOutOfBoundsError
return __val
示例13: I2C
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import read_byte [as 别名]
#.........这里部分代码省略.........
"""
combined = self._combineXLoLoHi(xloByte, loByte, hiByte)
return combined if combined < 8388608 else (combined - 16777216)
def _getSensorRawLoHi1(self, address, outRegs):
""" Return a scalar representing the combined raw signed 16 bit
value of the output registers of a one-dimensional sensor,
e.g. temperature.
'address' is the I2C slave address.
'outRegs' is a list of the output registers to read.
"""
# Read register outputs and combine low and high byte values
xl = self._readRegister(address, outRegs[0])
xh = self._readRegister(address, outRegs[1])
xVal = self._combineSignedLoHi(xl, xh)
# Return the scalar
return xVal
def _getSensorRawXLoLoHi1(self, address, outRegs):
""" Return a scalar representing the combined raw signed 24 bit
value of the output registers of a one-dimensional sensor,
e.g. temperature.
'address' is the I2C slave address.
'outRegs' is a list of the output registers to read.
"""
# Read register outputs and combine low and high byte values
xxl = self._readRegister(address, outRegs[0])
xl = self._readRegister(address, outRegs[1])
xh = self._readRegister(address, outRegs[2])
xVal = self._combineSignedXLoLoHi(xxl, xl, xh)
# Return the scalar
return xVal
def _getSensorRawLoHi3(self, address, outRegs):
""" Return a vector (i.e. list) representing the combined
raw signed 16 bit values of the output registers of a
3-dimensional (IMU) sensor.
'address' is the I2C slave address.
'outRegs' is a list of the output registers to read.
"""
# Read register outputs and combine low and high byte values
xl = self._readRegister(address, outRegs[0])
xh = self._readRegister(address, outRegs[1])
yl = self._readRegister(address, outRegs[2])
yh = self._readRegister(address, outRegs[3])
zl = self._readRegister(address, outRegs[4])
zh = self._readRegister(address, outRegs[5])
xVal = self._combineSignedLoHi(xl, xh)
yVal = self._combineSignedLoHi(yl, yh)
zVal = self._combineSignedLoHi(zl, zh)
# Return the vector
return [xVal, yVal, zVal]
def _readRegister(self, address, register):
""" Read a single I2C register. """
return self._i2c.read_byte_data(address, register)
def _readRegisters(self, address, register, count):
""" Read (up to 32) 'count' consecutive I2C registers. """
return self._i2c.read_i2c_block_data(address, register, count)
def _read(self, address):
""" Read a single byte from the I2C device without specifying a
register.
"""
return self._i2c.read_byte(address)
def _writeRegister(self, address, register, value):
""" Write a single byte to a I2C register. Return the value the
register had before the write.
"""
valueOld = self._readRegister(address, register)
self._i2c.write_byte_data(address, register, value)
return valueOld
def _write(self, address, value):
""" Write a single byte to the I2C device without specifying a
register.
"""
return self._i2c.write_byte(address, value)
def _testRegister(self, address, register):
""" Check, if a I2C register is readable/accessible. """
try:
return self._readRegister(address, register)
except:
return -1
示例14: enheden
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import read_byte [as 别名]
# -*- encoding: latin-1 -*-
# Dette program læser analog input fra PCF8591P chipens kanal #0.
from smbus import SMBus
from time import sleep
# Opret forbindelse til enheden(chipen).
bus = SMBus(1) # 1 Indikere at vi bruger enhedsfilen /dev/i2c-1.
# Addressen på chipen.
addresse = 74
# Referencespænding.
Vref = 4.25
konvateret = Vref / 256
print("Læs kanal 0 fra A/D.")
print("Udskriver aflæsningen når den forandres.")
print("Tryk CTRL+C for at stoppe.")
bus.write_byte(addresse, 0) # 0 Indikere at vi vil have data fra kanal 0.
sidste_aflaesning = -1
# Start en uendelig løkke og afbryd hvis ctrl+c bliver trykket.
while True:
aflaesning = bus.read_byte(addresse)
if (abs(sidste_aflaesning - aflaesning) > 1 ):
print "A/D læsning ", aflaesning, " som betyder ", round(konvateret * aflaesning, 2), " V."
sidste_aflaesning = aflaesning
sleep(0.01)
示例15: writeAOUT
# 需要导入模块: from smbus import SMBus [as 别名]
# 或者: from smbus.SMBus import read_byte [as 别名]
try:
MQTT.init()
last_reading =-1
last_reading1 =-1
last_reading2 =-1
last_reading3 =-1
for i in [1,255,1]:
writeAOUT(i)
while True:
time.sleep(0.1)
bus.write_byte(address, 0x40) # set control register to read channel 0
reading = bus.read_byte(address) # read A/D for starting AD conversion
reading = bus.read_byte(address) # read A/D value
if(abs(last_reading - reading) > 2):
last_reading = reading
MQTT.mqttc.publish("/RPiMower/World/PowerM1", reading)
if DEBUG:
print("1:",reading)
bus.write_byte(address, 0x41) # set control register to read channel 1
reading = bus.read_byte(address) # read A/D for starting AD conversion
reading = bus.read_byte(address) # read A/D value
if(abs(last_reading1 - reading) > 2):
last_reading1 = reading
MQTT.mqttc.publish("/RPiMower/World/PowerM2", reading)
if DEBUG: