The TMP102 temperature sensor breakout from Sparkfun is an easy to use thermometer that connects via I2C. This quick example shows how to use a TMP102 with Raspberry Pi and some simple Python code to get the current temperature.
Step 1:
Prerequisites
Run the following commands to install required packages:
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install i2c-tools
sudo apt-get install python-smbus
Step 2:
Enabling I2c device in Raspberry Pi. Pi is ready to go with I2C as far as enabling the hardware goes. You will need to open LX Terminal and enter the following command:
sudo nano /etc/modules
And add these two lines to the end of the file:
Step 3:
Depending on your distribution, you may also have to edit a file which comes under
sudo nano /etc/modprobe.d/raspi-blacklist.conf
blacklist spi-bcm2708
blacklist i2c-bcm2708
Edit and comment the above two lines by putting a “#” infront of them
#blacklist spi-bcm2708
#blacklist i2c-bcm2708
Step 4:
Now add a new user to the i2c group:
sudo adduser pi i2c
Step 5:
Reboot the machine by
sudo reboot
Step 6:
Connections: (GPIO.setmode(GPIO.BOARD)
TMP102 | Raspberry Pi |
GND | PIN 6 |
SCL | PIN 5 |
SDA | PIN3 |
V+ | 3.3v |
ADD0 | GND(PIN 9) |
When connected as above, the TMP102 uses the I2C address 0x48. To confirm this, run the following at the command line:
sudo i2cdetect -y 1
The resulting diagram should show the device at 0x48 by printing 48 in the corresponding cell.
Code
import smbus
import time
bus = smbus.SMBus(1)
data = bus.read_i2c_block_data(0x48, 0)
msb = data[0]
lsb = data[1]
print (((msb << 8) | lsb) >> 4) * 0.0625 #printing the temperature value in Celsius.
Execution of the code:
sudo python tmp102.py
TMP102 + Raspberry Pi in Action:
For queries:info@tenettech.com
Contact:080-26722726