Checking for 2 byte registers on TOF050C

Arduino forum,
The enclosed simple sketch just checks whether a register of the TOF050C laser sensor has 2 bytes available to be read.

For some reason the code will print that every register has 2 bytes.


#include <Wire.h>
#include <Adafruit_VL6180X.h>
int reg = 0x03;

#define TOF50C_ADDRESS 0x29  // I²C slave address
Adafruit_VL6180X vl = Adafruit_VL6180X();

void setup() {
 Serial.begin(9600);
 Wire.begin();
 if (!vl.begin()) {
  Serial.println("Failed to find TOF050C sensor!");
  while (1);
 }
 Serial.println("TOF050C ready!");
}

void loop() {
 uint8_t registerAddress = reg; // register to read
 Wire.beginTransmission(TOF50C_ADDRESS);
 Wire.write(registerAddress);
 Wire.endTransmission();
  
 Wire.requestFrom(TOF50C_ADDRESS, 2); // Request 2 bytes from the sensor
 delay(2);
 Serial.print("Register "); Serial.print(reg);
 if (Wire.available() == 2)
 {
  Serial.println(" Has 2 bytes");
 }else{
  Serial.println(" Does not have 2 bytes");
 }
 delay(1000); // Wait for a second before the next read
}

Any suggestions about what I'm doing wrong?
jerdon

Read and print them to see what you have there...

You ask for two bytes, and it returns two. Always.

If you want one byte, ask for one.

It would therefore be a good idea to know in advance how many bytes should be requested. The data sheet for the device gives the details.

Arduino forum,

STMicroelectronics doesn't publish a list of the registers for their devices so I don't know which are 1 byte and which are 2 byte.

Doesn't Wire.requestFrom receive a pass or fail back from the sensor if this particular register has 2 bytes or not?
jerdon

vl6180x.pdf

Not true. See post above. That particular sensor has 8-bit, 16-bit and 32-bit (four byte) registers. Furthermore, the multibyte format is MSB first.

Helpful guide to the Wire library.

In particular:

The function Wire.requestFrom() reads data. After it is finished, the received data is in a buffer (inside the Wire library). That data can be read with Wire.read(). The Wire.available() tells how many bytes are still in that buffer.

When there was a problem during the I2C bus activity, the received bytes up to that point are not reliable. With the Arduino Wire library it is not even possible to know if there are any reliable bytes before the bus error did happen. It is therefor better to first check for errors and if there are no errors, then read all the bytes.