Skip to content

Instantly share code, notes, and snippets.

@markadr
Last active October 19, 2017 22:45
Show Gist options
  • Save markadr/63b8eaf4248f0054c241 to your computer and use it in GitHub Desktop.
Save markadr/63b8eaf4248f0054c241 to your computer and use it in GitHub Desktop.
Example code to deal with the TMP102 Temp Sensor via the PI4J API on a RaspberryPi.
import com.pi4j.io.i2c.I2CBus;
import com.pi4j.io.i2c.I2CDevice;
import com.pi4j.io.i2c.I2CFactory;
import com.pi4j.system.SystemInfo;
import com.pi4j.temperature.TemperatureConversion;
import com.pi4j.temperature.TemperatureScale;
import java.io.IOException;
/**
*
* @author Mark de Reeper
*/
public class TMP102 {
/**
* http://www.zagrosrobotics.com/files/tmp102.pdf
*
DEVICE TWO-WIRE ADDRESS A0 PIN CONNECTION
1001000 (0x48) Ground
1001001 (0x49) V+
1001010 (0x4A) SDA
1001011 (0x4B) SCL
*/
public static final int DEVICE_ADDRESS_GROUND = 0x48;
public static final int DEVICE_ADDRESS_VPLUS = 0x49;
public static final int DEVICE_ADDRESS_SDA = 0x4A;
public static final int DEVICE_ADDRESS_SCL = 0x4B;
private I2CBus bus = null;
private I2CDevice device = null;
public TMP102(int sensorAddress) throws IOException, InterruptedException {
if (SystemInfo.getBoardType().equals(SystemInfo.BoardType.ModelA_Rev0)) {
bus = I2CFactory.getInstance(I2CBus.BUS_0);
} else {
bus = I2CFactory.getInstance(I2CBus.BUS_1);
}
if (bus != null) {
device = bus.getDevice(sensorAddress);
}
}
public double getTemperature(TemperatureScale scale) throws IOException {
// default is Celsius
double result = getReadingFromDevice() * 0.0625;
switch (scale) {
case CELSIUS :
break;
case FARENHEIT :
result = TemperatureConversion.convertCelsiusToFarenheit(result);
break;
case KELVIN :
result = TemperatureConversion.convertCelsiusToKelvin(result);
break;
case RANKINE :
result = TemperatureConversion.convertCelsiusToRankine(result);
break;
}
return result;
}
private void close() throws IOException {
if (bus != null) {
bus.close();
}
}
private int getReadingFromDevice() throws IOException {
int result = 0;
if (device != null) {
// http://www.raspberrypi.org/phpBB3/viewtopic.php?f=81&t=31272
// http://bildr.org/2011/01/tmp102-arduino/
byte[] tempBuffer = new byte[2];
int bytesRead = device.read(tempBuffer, 0, 2);
if (bytesRead == 2) {
int MSB = tempBuffer[0] < 0 ? 256 + tempBuffer[0] : tempBuffer[0];
int LSB = tempBuffer[1] < 0 ? 256 + tempBuffer[1] : tempBuffer[1];
result = ((MSB << 8) | LSB) >> 4;
}
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment