Trying to work around a glitching bug in the L3G4200D gyroscope, I ran into what looks like another bug, this time in Wire.
// this is broken. for some reason, trying to request two bytes at a time from wired messes up
int readRegister2_isbroken(int deviceAddress, byte address){
Wire.beginTransmission(deviceAddress);
Wire.write(address); // register to read
Wire.endTransmission();
Wire.requestFrom(deviceAddress, 2); // we want two bytes, little endian
while(Wire.available() < 2) { delay(1); }
byte b0 = Wire.read();
byte b1 = Wire.read();
return ((b1 << 8) | b0);
}
int readRegister2b(int deviceAddress, byte address){
Wire.beginTransmission(deviceAddress);
Wire.write(address);
Wire.endTransmission();
Wire.requestFrom(deviceAddress, 1);
while(!Wire.available()) { delay(1); }
byte b0 = Wire.read();
Wire.beginTransmission(deviceAddress);
Wire.write(address+1);
Wire.endTransmission();
Wire.requestFrom(deviceAddress, 1);
while(!Wire.available()) { delay(1); }
byte b1 = Wire.read();
return ((b1 << 8) | b0);
}
The two above should be functionally equivelent, but the first one produces bad data.
I discovered this while trying to read all three registers (6 bytes) at once to possibly work around the glitch. (some suspect registers are being updated while I am trying to read them) Trying to read all six registers into an array in one swipe tends to produce six of the same number, though not always. Most of the time I get 253-255. Which is annoying, since that's also what the glitch tends to return. Sent me chasing my tail for a time.
(fyi the GY-81 schematic indicates mosfet level buffers with pull-ups on the I2C lines)
Just for laughs I tried reversing the b0/b1 reads to see if it was an endianness or stack-vs-fifo issue with Wire, but that didn't help.
Since Wire doesn't support a parameter in the Read function, I assume it's just never been intended to deal with more than one byte at a time, in single file? or is there something a little more subtle I'm missing here? This is a GY-81 tied ti an Arduino Micro, just the four wires and nothing else.