Challenge - 5 Problems
I2C Sensor Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this I2C sensor read code?
Consider this Python code snippet running on a Raspberry Pi to read 2 bytes from an I2C sensor at address 0x48. What will be printed?
Raspberry Pi
import smbus bus = smbus.SMBus(1) address = 0x48 raw = bus.read_i2c_block_data(address, 0, 2) value = (raw[0] << 8) | raw[1] print(value)
Attempts:
2 left
💡 Hint
The read_i2c_block_data returns a list of integers representing bytes.
✗ Incorrect
The code reads two bytes from the sensor and combines them into a single 16-bit integer using bit shifting and bitwise OR. The print outputs this integer value.
🧠 Conceptual
intermediate1:00remaining
Which I2C bus number should you use on Raspberry Pi 4?
On a Raspberry Pi 4, which bus number corresponds to the default I2C pins (SDA, SCL) you should use in smbus.SMBus()?
Attempts:
2 left
💡 Hint
The default I2C bus on Raspberry Pi models after version 1 is bus 1.
✗ Incorrect
The Raspberry Pi 4 uses I2C bus 1 for the default SDA and SCL pins. Bus 0 is reserved for system use.
🔧 Debug
advanced2:00remaining
Why does this I2C read code raise an IOError?
This code snippet raises an IOError when run on Raspberry Pi. What is the most likely cause?
import smbus
bus = smbus.SMBus(1)
address = 0x50
data = bus.read_byte(address)
print(data)
Attempts:
2 left
💡 Hint
IOError usually means no device responded at that address.
✗ Incorrect
An IOError during I2C read usually means the device at the given address is not present or not responding. The bus number and method usage are correct.
📝 Syntax
advanced2:30remaining
Which option correctly reads a signed 16-bit value from I2C sensor?
You want to read a signed 16-bit integer from an I2C sensor at address 0x40 using smbus. Which code snippet correctly converts the two bytes to a signed integer?
Raspberry Pi
import smbus bus = smbus.SMBus(1) address = 0x40 raw = bus.read_i2c_block_data(address, 0, 2)
Attempts:
2 left
💡 Hint
The sensor sends high byte first, then low byte. Use parentheses carefully.
✗ Incorrect
The sensor data is big-endian: high byte first. Option C correctly shifts raw[0] by 8 bits and ORs with raw[1]. It then converts to signed by subtracting 65536 if value > 32767.
🚀 Application
expert2:00remaining
How many bytes will this I2C read return?
You run this code on Raspberry Pi to read data from an I2C sensor:
import smbus
bus = smbus.SMBus(1)
address = 0x68
count = 6
data = bus.read_i2c_block_data(address, 0x3B, count)
print(len(data))
How many bytes will be printed?
Attempts:
2 left
💡 Hint
The count argument specifies how many bytes to read.
✗ Incorrect
The read_i2c_block_data method reads exactly the number of bytes specified by the count argument. Here count=6, so 6 bytes are returned.
