Interfacing thermocouple with Raspberry Pi using MAX31855

Reading thermocouple data on Raspberry Pi using JAVA and Pi4J with the help of MAX31855 14 bit thermocouple to digital converter. The MAX31855 performs cold-junction compensation and digitizes the signal from a K-, J-, N-, T-, S-, R-, or E-type thermocouple. The data is output in a signed 14-bit, SPI-compatible, read-only format. This converter resolves temperatures to 0.25°C, allows readings as high as +1800°C and as low as -270°C, and exhibits thermocouple accuracy of ±2°C for temperatures ranging from -200°C to +700°C for K-type thermocouples. Check here for more details. 


import java.nio.ByteBuffer;


public class MAX31855_Thermocouple {
    public static SpiDevice spi = null;
    public static void main(String args[]) throws InterruptedException, IOException {
    	System.out.println("Starting Thermocouple Application.");
        spi = SpiFactory.getInstance(SpiChannel.CS0,SpiDevice.DEFAULT_SPI_SPEED,SpiDevice.DEFAULT_SPI_MODE);
        	System.out.println(getConversionValue()); //Print out red ADC Sample Counts
    public static double getConversionValue() throws IOException {

        byte data[] = new byte[] {0,0, 0, 0};// Dummy payloads. It's not responsible for anything.
        byte[] result = spi.write(data); //Request data from MAX31855 via SPI with dummy pay-load
        if((result[0] & 128)==0 && (result[1] & 1)==1 ) {//Sign bit is 0 and D16 is high corresponds to Thermocouple not connected.
            System.out.println("Thermocouple is not connected");
            return 0;
        String stringResult=String.format("%32s",Integer.toString(ByteBuffer.wrap(result).getInt(), 2)).replace(' ', '0');
        double valInt=0.0;
        if(stringResult.charAt(0)=='1' ){  //Checking for signed bit. If need to convert to 2's Complement.
         	StringBuilder onesComplementBuilder = new StringBuilder();
        	for(char bit : stringResult.substring(0, 12).toCharArray()) {
        	    onesComplementBuilder.append((bit == '0') ? 1 : 0);  // if bit is '0', append a 1. if bit is '1', append a 0.
        	String onesComplement = onesComplementBuilder.toString();
        	valInt = -1*( Integer.valueOf(onesComplement, 2) + 1); // two's complement = one's complement + 1. This is the positive value of our original binary string, so make it negative again.
        	valInt=Integer.parseInt(stringResult.substring(0, 12),2); //+ve no convert to double value
        if(stringResult.charAt(12)=='1') //Check for D18 and D19 for fractional values
        return valInt;

You can find the code repository here .
MAX31855 Datasheet:

Buy MAX31855:
Subscribe YouTube:

Guys Subscribe to my channel for the latest content in your inbox.
Support me to keep going.

Website :
Twitter :
YouTube :
Instagram :

Related posts

Leave a Comment