#Code is offered under no licesne with no warranty, Please be aware that negitive temperatures have not been implemented in this file and it currently functions under python 2.7, which is obsolete. #Michael Rudi #Fourm Post https://forum.digikey.com/t/reading-temperature-data-from-a-mcp9808-using-a-raspberry-pi/4962 import smbus #to use I2C functions import time #To use time.sleep(Seconds) #Helper function to seperate MSB and LSB values in the temperature register def a16bit_to_MSB_LSB(data): return data[8:16], data[0:8] bus = smbus.SMBus(1) #assign the bus MCP9808 = 0x1C #Devices I2C address goes here, typically 0x18 on the Adafruit breakout board #turn on the MCP9808 by writing to status bus and clearing any possible previous shutoff command bus.write_byte_data(MCP9808,0x1,0) #Primary Loop for check in range(5): time.sleep(3) # 3 second loop timer #Pool the contents of Register 0x05 for temperature data as a MSB, LSB pair; #This comes back as a 16bits, so we use 16bit_to_MSB_LSB above to seperate the binary string data temp_MSB, temp_LSB = a16bit_to_MSB_LSB(format(bus.read_word_data(MCP9808,0x5), "016b")) #configure data into a MMMMLLLL.LLLL floating point binary format. (M = MSB, L = LSB) tempInt = int((temp_MSB + temp_LSB)[4:12],2) tempDec = float(int(temp_LSB[4:8],2)) / 16 #Calculate the temperature tempC = float(tempInt) + tempDec tempF = tempC * 9/5 + 32 #Print the results print ('MSB of 0x05 is ' + temp_MSB) print ('LSB of 0x05 is ' + temp_LSB) print (str(tempC) + " degrees C on check " + str(check+1)) print (str(tempF) + " degrees F on check " + str(check+1)) #turn off the MCP9808 for power saving bus.write_byte_data(MCP9808,0x1,1) #end of file # print ('no response from ' + str(NoResponses)) # NoResponses = []