TMP1x2 Temperature Sensor Driver in Rust

TMP102 measuring ambient temperature


I have continued writing several Rust device drivers. Today I present you a Rust driver for the TMP102 and TMP112 high-accuracy, low-power, digital temperature sensors.

The devices

This driver is compatible with both the TMP102 device as well as the TMP112 family of devices, including TMP112A, TMP112B and TMP112N.

These temperature sensors are highly linear and do not require complex calculations or lookup tables to derive the temperature. The on-chip 12-bit ADC offers resolutions down to 0.0625°C.

The TMP102 device is a digital temperature sensor ideal for NTC/PTC thermistor replacement where high accuracy is required. The device offers an accuracy of +/-0.5°C without requiring calibration or external component signal conditioning.

The TMP112 family of devices are digital temperature sensors designed for high-accuracy, low-power, NTC/PTC thermistor replacements where high accuracy is required. The TMP112A and TMP112B offers 0.5°C accuracy and are optimized to provide the best PSR performance for 3.3V and 1.8V operation respectively, while TMP112N offers 1°C accuracy.

The communication is done serially through an I²C, bidirectional bus.

Datasheets: TMP102, TMP112x

You can buy a module board containing this from AliExpress or eBay.

Using the driver

To use the device from Rust, you have to add the tmp1x2 crate to your project as well as a concrete implementation of the embedded-hal traits. For example if you are using the Raspberry Pi running Linux (see driver-examples for bare-metal hardware):

# Cargo.toml
tmp1x2 = "0.2"
linux-embedded-hal = "0.3"

This is an example program which will measure the temperature and print it (in Celsius) (source):

extern crate linux_embedded_hal as hal;
extern crate tmp1x2;

use tmp1x2::{SlaveAddr, Tmp1x2};

fn main() {
let dev = hal::I2cdev::new("/dev/i2c-1").unwrap();
let address = SlaveAddr::default();
let mut sensor = Tmp1x2::new(dev, address);
let temperature = sensor.read_temperature().unwrap();
println!("Temperature: {:.1}ºC", temperature);

I also created an example program that runs on the STM32F3Discovery board which continuously measures the temperature and prints it on an OLED display. You can find the application source code here.

In the driver-examples repository you can find further examples which you can adapt to do other things with this device.

Where to go from here?

There is much more information and example programs in the crate documentation.
Please give this driver a try and report any issues you may encounter in the issue tracker.
Feedback, suggestions and improvements are gladly welcome.

What’s next?

I have been writing many other platform-agnostic Rust drivers although I am slow to announce them here. If you want to know what I am currently working on you can follow me on github.

Thanks for reading and stay tuned!

Links: Source code - Crate - Documentation