Bird
0
0
Raspberry Piprogramming~20 mins

smbus2 library for I2C in Raspberry Pi - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
I2C Master with smbus2
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
1:30remaining
What is the output of this smbus2 read_byte code?

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?

Raspberry Pi
from smbus2 import SMBus

with SMBus(1) as bus:
    data = bus.read_byte(0x20)
print(data)
A90
B0x5A
Cb'\x5A'
DError: SMBus object has no attribute 'read_byte'
Attempts:
2 left
💡 Hint

Remember that read_byte returns an integer representing the byte value.

🧠 Conceptual
intermediate
1:00remaining
Which smbus2 method writes a block of bytes to a device?

You want to send multiple bytes at once to an I2C device using smbus2. Which method should you use?

Awrite_byte_data(addr, cmd, val)
Bwrite_byte(addr, val)
Cwrite_block_data(addr, cmd, vals)
Dread_block_data(addr, cmd)
Attempts:
2 left
💡 Hint

Look for a method that explicitly mentions writing a block of data.

🔧 Debug
advanced
2:00remaining
Why does this smbus2 code raise an IOError?

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?

AThe bus number 1 is invalid on Raspberry Pi
BThe SMBus object was not opened with a context manager
CThe <code>read_byte_data</code> method requires a third argument
DThe device at address 0x50 is not connected or not responding
Attempts:
2 left
💡 Hint

Consider hardware connection and device presence on the I2C bus.

📝 Syntax
advanced
1:30remaining
Which option correctly writes a single byte using smbus2?

Choose the correct syntax to write the byte 0x1F to register 0x05 of a device at address 0x30 using smbus2:

Abus.write_byte_data(0x30, 0x05, 0x1F)
Bbus.write_byte(0x30, 0x05, 0x1F)
Cbus.write_byte_data(0x30, 0x1F)
Dbus.write_byte_data(0x05, 0x30, 0x1F)
Attempts:
2 left
💡 Hint

Remember the order of parameters: device address, register, then value.

🚀 Application
expert
2:00remaining
How many bytes are read by this smbus2 block read?

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))?

A0
B6
C1
DRaises TypeError
Attempts:
2 left
💡 Hint

The third argument to read_i2c_block_data specifies how many bytes to read.