 # Function Return

I have a function that I copied from the internet to return the temperature from a MAX6675. I don't understand what the return line is doing to the value obtained from the spi.

``````return((int)(temp_reading >> 5));
``````

Is it converting the variable temp_reading to an int? then what does the >> 5 do to the variable temp_reading?

Thanks John

The value of temp_reading is shifted 5 positions / bits to the right. That is equivalent to a division by 32. Then the value is converted to an int by means of casting.

The bottom 3 bits from the chip are not temperature data and the temperature value is to a resolution of 0.25C.

Thus the shift-right by 5 bits discards the 3 other bit and divides the temperature reading by 4 to give degrees C directly.

Is it because the SPI is in BIN the shift bits just pushes the unwanted bits off?

I'm not sure I understand how the bit shift divides the number... and how can I get the 0.25C resolution?

Thanks for the help. John

I'm not sure I understand how the bit shift divides the number...

A single bit shift right divides by 2.

Thus 8 in binary is 1000. Shift it right by 1 place, you get 100, which is 4. Obviously, odd number don't get rounded, but you can get around this by adding half before shifting.

thus, nine is 1001 in binary, so dividing by 2 would give 100 or 4, since the half is lost. If you add 1 before shifting (which is the same as adding a half after shifting), you get 1010, which didided by 2 is 101 or 5 decimal.

If you shift two places right, you divide by 4, three places by 8, four place by 16 and so on.

Is it because the SPI is in BIN the shift bits just pushes the unwanted bits off?

I'm not sure I understand how the bit shift divides the number... and how can I get the 0.25C resolution?

Suppose TempReading TR holds 01101010 Accoring to the info above this is 011 - integer part 01 - decimal part and 010 other 3 bits

TR 01101010 TR >> 1 ==> 00110101 (all bit are moved one position to the right, and from the left 0's are shifted in. TR >> 5 ==> 00000110 that leaves only the integer part.

If you want to have the decimal part to you must:

float f() { ... return (TempRead >> 3)* 0.25; // strip of the unwanted bits and then you have 0.25 C units }

Rob

Rob,

Thanks so much for explaining this. I have it working now.

Just so I understand the binary number is actually degrees C / 4 to get the 0.25C resolution? So the part about multiplying that number by 0.25 converts it to degrees C with a precision of 0000.00.

So before the multiplication a raw number of say 105 is what the SPI brings back which is 105 quarters of degrees C. So 105 * 0.25 = 26.25C

This is so much fun...

Thanks John