Consider this Arduino code snippet that reads a byte from an I2C sensor at address 0x40. What will be printed on the Serial Monitor?
Wire.begin(); Wire.beginTransmission(0x40); Wire.write(0x00); Wire.endTransmission(); Wire.requestFrom(0x40, 1); int data = Wire.read(); Serial.println(data);
Wire.requestFrom() asks the sensor for bytes, and Wire.read() reads them. The sensor returns a byte, which is printed.
The code correctly requests 1 byte from the sensor at address 0x40 and reads it. The value printed is the sensor's byte, not zero or error.
In Arduino I2C communication, which function starts talking to a sensor device?
Think about which function tells the sensor you want to send data first.
Wire.beginTransmission(address) starts communication by telling the sensor you want to send data.
Look at this Arduino code snippet. It always prints -1. Why?
Wire.begin(); Wire.requestFrom(0x50, 1); int val = Wire.read(); Serial.println(val);
Think about what the sensor expects before sending data.
The sensor needs a register address sent first with Wire.beginTransmission() and Wire.write() before Wire.requestFrom(). Without this, no data is ready, so Wire.read() returns -1.
Find the option that fixes the syntax error in this Arduino I2C code snippet:
Wire.beginTransmission(0x68) Wire.write(0x10); Wire.endTransmission();
Look carefully at missing punctuation in the code.
The first line is missing a semicolon at the end, causing a syntax error. Adding it fixes the code.
This Arduino code requests data from an I2C sensor. How many bytes will be read and printed?
Wire.beginTransmission(0x20);
Wire.write(0x01);
Wire.endTransmission();
Wire.requestFrom(0x20, 3);
while(Wire.available()) {
Serial.print(Wire.read());
Serial.print(",");
}Check the number requested in Wire.requestFrom() and how many bytes are printed.
The code requests 3 bytes from the sensor and prints each byte while available, so 3 bytes are read and printed.
