Hello,
I am trying to read the temperature of an I2C sensor but I can't seem to get it right. I had it working at one time which makes it even more frustrating. I am using the BMP180 sensor and you can find the doc here: https://cdn-shop.adafruit.com/datasheets/BST-BMP180-DS000-09.pdf
My code:
-write function:
void I2C_write (byte I2C_address, byte register_address, byte data)
{
Wire.begin(I2C_address);
Wire.write(register_address);
Wire.write(data);
Serial.print("Error code (write): ");Serial.println(Wire.endTransmission());
}
-read function:
short I2C_read (byte I2C_address, byte register_address, short number_bytes)
{
Wire.beginTransmission(I2C_address);
Wire.write(register_address);
Serial.print("Error code (read): ");Serial.println(Wire.endTransmission());
Wire.requestFrom(I2C_address, number_bytes);
while(Wire.available() == 0){};
short combined;
byte MSB = Wire.read();
Serial.print("MSB: "); Serial.println(MSB);
byte LSB = Wire.read();
Serial.print("LSB: "); Serial.println(LSB);
combined = (MSB << 8) + LSB;
return combined;
}
-main code to get the temp
void loop() {
I2C_write(I2C_address, 0xF4, 0x2E); //Send command to obtain temp
delay(5); //delay between write and read as mentioned in the doc
Serial.println(I2C_read(I2C_address, 0xF6, 2)); //read and display the uncompensated temp value
delay(3000);
}
this results in:
Error code (write): 2
Error code (read): 0
MSB: 128
LSB: 0
-32768
Error code (write): 0
Error code (read): 0
MSB: 128
LSB: 0
-32768
Error code (write): 0
Error code (read): 0
MSB: 128
LSB: 0
-32768
...
As you can see the first time I write the "Obtain temp" command I get the error code '2' from endTransmission() which means the slave didn't ack the address... However all subsequent writes and reads don't result in any errors.
The readings (both MSB and LSB and therefore the combined value) are not influenced by the write error and stay the same. Even if I warm the sensor up with my hand.
The 'combined' var obviously experiences an overflow but I don't understand how a 16bit var can be overflown by two 8 bit vars which are combined with bitshifting...
It would be amazing if someone could help me out. I really enjoy programming and problem solving but this isn't funny anymore...