The below Arduino code snippet shows a function that should return a byte read from the Output Register of an I/O Expander TCA9535 via I2C. I oriented my code at the TCA9535 Datasheet Figure 7-8, seen here: https://i.sstatic.net/GgNAQ.png.
However, calling readOutputRegister()
always returns 255
.
uint8_t readOutputRegister(){
Wire.beginTransmission(0x20); // Set Write mode (RW = 0)
Wire.write(0x02); // Read-write byte Output Port 0
// Repeated START
Wire.beginTransmission(0x21); // Set Read mode (RW = 1)
uint8_t res = Wire.read();
// Stop condition
Wire.endTransmission();
return res;
}
Here is the link for the datasheet of the TCA9535 I/O Expander I am using: https://www.ti.com/lit/ds/symlink/tca9535.pdf
First, from Wire.endTransmission()
reference page.
This function ends a transmission to a peripheral device that was begun by beginTransmission() and transmits the bytes that were queued by write().
For Wire library, many people think Wire.write()
would send the data, it is actually not, it only put the data on a queue. Data will only get send when you call Wire.endTransmission()
.
So you need to call Wire.endTransmission()
after Wire.write(0x02)
.
Secondly, to read the data, it needs to call Wire.requestFrom()
and also need to check if data has received with Wire.available()
before reading the data.
Wire.beginTransmission(0x20); // Set Write mode (RW = 0)
Wire.write(0x02); // Read-write byte Output Port 0
if (Wire.endTransmission() != 0) {
// error
}
else {
Wire.requestFrom(0x20, 1); // request 1 byte from the i2c address
if (Wire.available()) {
uint8_t c = Wire.read();
}
}