Reading a temperature
One read of an LM75 is a write of the register number, a repeated start, and two bytes back. Put the bytes together as a signed number, divide by 256, and that is the temperature in degrees.
Everything from the last seven lessons comes together in one read. To read the temperature from an LM75 at 0x48, the ESP32:
- Sends a START: SDA falls while SCL is high. No data bit ever does that, so every chip knows a message is beginning.
- Sends the address, 0x48, and a 0: write.
- Gets an ACK from the chip on the ninth clock.
- Writes the register number, 0x00, and gets another ACK.
- Sends a repeated START, keeping the bus, then 0x48 with a 1: read. The chip acknowledges.
- Clocks in two bytes that the chip drives onto SDA. The ESP32 ACKs the first and sends a NACK after the second: that is enough.
- Sends a STOP: SDA rises while SCL is high, and the bus is free.
From two bytes to degrees
At 25.5 °C the two bytes are 0x19 and 0x80. Side by side they are 0x1980, which is 6528; divide by 256 and you get 25.5. Read as a signed 16-bit number, the same arithmetic works below zero.
Wire.beginTransmission(0x48);
Wire.write(0x00); // the temperature register
Wire.endTransmission(false); // false: a repeated start, not a stop
Wire.requestFrom(0x48, 2);
int16_t raw = (Wire.read() << 8) | Wire.read();
float celsius = raw / 256.0;The int16_t matters. On an ESP32 an int is 32 bits, and without the
cast a reading below zero comes out as a large positive number.
Every I2C sensor is read like this: write which register, then read bytes. What changes from chip to chip is the address, the register numbers, and the arithmetic, and those are in its datasheet.
Edit this page — content/fundamentals/i2c/reading-a-temperature.mdx
Discuss this article
Ask about this page. The answer stays here, on the page it belongs to, for whoever hits the same wall next.