Challenge - 5 Problems
I2C Command 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 write command code?
Consider the following Python code snippet running on a Raspberry Pi to write a byte to an I2C device. What will be printed when this code runs successfully?
Raspberry Pi
import smbus2 bus = smbus2.SMBus(1) address = 0x20 try: bus.write_byte(address, 0xFF) print("Write successful") except Exception as e: print(f"Error: {e}")
Attempts:
2 left
💡 Hint
The code tries to write a byte and prints a success message if no error occurs.
✗ Incorrect
The code writes a byte 0xFF to the device at address 0x20. If the device is connected and responds, the write succeeds and prints 'Write successful'.
🧠 Conceptual
intermediate1:30remaining
Which I2C address format is correct for smbus2 write commands?
When using smbus2 on Raspberry Pi to write to an I2C device, which address format should you use?
Attempts:
2 left
💡 Hint
I2C addresses are usually 7 bits; the library handles the read/write bit.
✗ Incorrect
smbus2 expects the 7-bit address without the read/write bit. The library adds the read/write bit automatically.
🔧 Debug
advanced2:30remaining
Why does this I2C write command raise an error?
This code snippet raises an error when trying to write a byte to an I2C device. What is the most likely cause?
Raspberry Pi
import smbus2 bus = smbus2.SMBus(1) address = 0x20 bus.write_byte_data(address, 0x01)
Attempts:
2 left
💡 Hint
Check the method signature for write_byte_data.
✗ Incorrect
write_byte_data requires three arguments: address, command/register, and data byte. The code misses the data byte argument.
📝 Syntax
advanced2:00remaining
Which option correctly writes a block of bytes to an I2C device?
You want to write the bytes [0x01, 0x02, 0x03] starting at register 0x10 to an I2C device at address 0x20 using smbus2. Which code snippet is syntactically correct and will run without error?
Attempts:
2 left
💡 Hint
Check the exact method name in smbus2 for block writes.
✗ Incorrect
The correct method is write_i2c_block_data. Other options are invalid method names and cause AttributeError.
🚀 Application
expert3:00remaining
What is the value of 'result' after this I2C write and read sequence?
Given the following code that writes a byte to register 0x05 and then reads a byte back from the same register, what is the value of 'result' if the device echoes the written byte?
Raspberry Pi
import smbus2 bus = smbus2.SMBus(1) address = 0x20 bus.write_byte_data(address, 0x05, 0xAB) result = bus.read_byte_data(address, 0x05) print(result)
Attempts:
2 left
💡 Hint
0xAB in decimal is 171. The device echoes the byte written.
✗ Incorrect
The code writes 0xAB (decimal 171) to register 0x05 and reads it back. If the device echoes correctly, result is 171.
