Consider this Python code snippet using smbus2 to read a byte from an I2C device at address 0x20 on bus 1:
from smbus2 import SMBus
with SMBus(1) as bus:
data = bus.read_byte(0x20)
print(data)Assuming the device returns the byte 0x5A, what will be printed?
from smbus2 import SMBus with SMBus(1) as bus: data = bus.read_byte(0x20) print(data)
Remember that read_byte returns an integer representing the byte value.
The read_byte method returns the byte as an integer. The hexadecimal 0x5A equals decimal 90, so print(data) outputs 90.
You want to send multiple bytes at once to an I2C device using smbus2. Which method should you use?
Look for a method that explicitly mentions writing a block of data.
write_block_data sends a list of bytes (vals) to the device at addr starting at register cmd. Other methods write single bytes or read data.
Examine this code snippet:
from smbus2 import SMBus bus = SMBus(1) value = bus.read_byte_data(0x50, 0x10) bus.close() print(value)
It raises an IOError when run. What is the most likely cause?
Consider hardware connection and device presence on the I2C bus.
An IOError usually means the device at the given address did not acknowledge the request. This often happens if the device is disconnected or powered off.
Choose the correct syntax to write the byte 0x1F to register 0x05 of a device at address 0x30 using smbus2:
Remember the order of parameters: device address, register, then value.
write_byte_data takes three arguments: device address, register address, and the byte value to write. Option A matches this order and syntax.
Given this code snippet:
from smbus2 import SMBus
with SMBus(1) as bus:
data = bus.read_i2c_block_data(0x40, 0x00, 6)
print(len(data))What is the output of print(len(data))?
The third argument to read_i2c_block_data specifies how many bytes to read.
The method read_i2c_block_data reads the specified number of bytes (6 here) from the device starting at register 0x00. The returned list length is 6.
