Temperature Controller using Arduino Uno


Temerature with the MAX6675

SPI

From the data sheet I find the following info:

Setting up the SPI in the Uno

The Includes and Defines

	#include <SPI.h> // The SPI library
	#define CS_MAX 10 // MAX6675 CS (Chip Select) Line
	

The Temperature Function

	int GetTemperature (void)
	{
	unsigned int temp_reading;

	// stop any conversion process
	delay(5);
	digitalWrite(CS_MAX,LOW); // Set MAX7765 /CS Low
	delay(5);
  
	// initiate a new conversion
	digitalWrite(CS_MAX,HIGH); // Set MAX7765 /CS High
	delay(250); // wait for conversion to finish..
  
	// read result
	digitalWrite(CS_MAX,LOW); // Set MAX7765 /CS Low
	delay(1);
  
	temp_reading = SPI.transfer(0xff) << 8;  
	temp_reading += SPI.transfer(0xff);  

	digitalWrite(CS_MAX,HIGH); // Set MAX7765 /CS High
	delay(1);
  
	// Bit D2 is normally low and goes high if the thermocouple input is open.
	if(bitRead(temp_reading,2) == 1) // No Connection
		{
			return(-1); // No Connection Error
		}
		else
		{
			return((int)(temp_reading >> 5)); //Convert to Degc
		}
	}
	

SPI shifts 8 bits out and 8 bits in at the same time. To read a byte you need to send a byte. The 0xff is a hexadecimal (base 16) constant equivalent to 255. Depending on the slave device, the value being sent when reading data may or may not be important.

<< 8 means "shift left 8 bits". This is to put the received byte in the upper 8 bits of a 16-bit word. += means "add the value on the right to the variable on the left. It puts the received byte in the lower half of the 16-bit word.

All together it reads two 8-bit bytes from the SPI device and stores them as a 16-bit integer.

The Setup

	void setup()
	{
	  Serial.begin(9600);

	  pinMode(CS_MAX,OUTPUT); // MAX6675/6674 /CS Line must be an output for hardware SPI
	  digitalWrite(CS_MAX,HIGH); // Set MAX7765 /CS High

	  SPI.begin(); // Init SPI
	  SPI.setBitOrder(MSBFIRST); // Set the order of the bits shifted out of and into the SPI bus
	  SPI.setDataMode(SPI_MODE1); // Capture data on clock's falling edge.
	  SPI.setClockDivider(SPI_CLOCK_DIV4); // Set SPI data rate to 4mhz.
	}
	

Reading the Temperature

	void loop()
	{
	int temperature = 0;

	while(1)
	  {
	    delay(1000);
	    temperature = GetTemperature(); 
	    if(temperature == -1)
	    {
	      Serial.println("No Connection");
	    }
	    else
		  {
	      Serial.print(temperature,DEC); 
	      Serial.println(" DegC");
	    }
	  }
	}