Reading a value from the I2C port with an Arduino
Just to make things complete, I'd like to paste my most recent experiment here. It's about controlling the I2C pins by reading from a temperature sensor and displaying it over the serial port.
My sensor is a LM75 type which has the default address 0x90 which boils down to an address setting of 0x48 (don't ask me why). But here's some funny code that actually works:
#include <Wire.h> #define address 0x48 void setup() { Wire.begin(); Serial.begin(9600); } void loop() { Wire.beginTransmission(address); Wire.send(0x00); Wire.requestFrom(address, 1); int temperature; if (Wire.available()) { temperature = Wire.receive(); } Wire.endTransmission(); Serial.println("-----------"); Serial.println(temperature); delay(1000); }
Please note that the communication pattern with the device is very much relative to the chip you're using. I found the following texts very helpful, from which I also took some crucial ideas:
- http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1252352897/0 - I also have such a board
- http://www.nearfuturelaboratory.com/2007/01/11/arduino-and-twi/
- http://naneau.nl/2009/01/18/arduino-and-an-i2c-temperature-sensor/ - This is fantastic!!
- http://blog.makezine.com/archive/2008/05/hook_up_an_arduino_to_i2c.html That's good also!
Some notes on I2C addresse. The above given example requests the value from an address 0x48, whereas the datasheet and some other sources explain that the address of the temp sensor is 0x90. What's the difference? Let's convert these values to their binary form:
0x48 = 1001000 0x90 = 10010000
You see that the only difference is the last bit. Remember that the I2C bus has 7 bits for the addressing. The last bit defines the reading or writing direction. So the address is eventually just composed out of the first 7 bits. Omit the last bit and try again. Use a binary calculator for calculations such as these.
It is also interesting to know that temperature sensors of the same type use the same base addresses. I have been using the temp sensors LM75 and MPC9802 and they have the same base addresses. Notably the LM75 product from Horter&Kalb has the possibility to set the three last address bits through a jumper array. So you can operate a maximum of 8 temp sensors on one I2C bus.
Note that it would be possible to state the address alternatively in the binary form:
#define address B1001000