Skip to content

Instantly share code, notes, and snippets.

@aolkin
Last active April 1, 2024 02:13
Show Gist options
  • Save aolkin/6d510aee6f0a375ffe85 to your computer and use it in GitHub Desktop.
Save aolkin/6d510aee6f0a375ffe85 to your computer and use it in GitHub Desktop.
Quick library to read from the MLX90614 with python on a Raspberry Pi, using the Adafruit_I2C library

Note that the following code must be run at every boot for this to work, because of the repeated-start requirement:

sudo su -c 'echo "Y" > /sys/module/i2c_bcm2708/parameters/combined'

#!/usr/bin/env python3
from adafruit.i2c import Adafruit_I2C
class Melexis:
def __init__(self, addr=0x5A, fahrenheit=False):
self._i2c = Adafruit_I2C(addr)
self.mode = fahrenheit
def readAmbient(self):
return self._readTemp(0x06)
def readObject(self):
return self._readTemp(0x07)
def readObject2(self):
return self._readTemp(0x08)
def getDifference(self):
"""Returns how much warmer the object is than the ambient
temperature."""
return self.readObject() - sensor.readAmbient()
def _readTemp(self, reg):
temp = self._i2c.readS16(reg)
temp = temp * .02 - 273.15
if self.mode:
return (temp * 9 / 5) + 32
else:
return temp
if __name__ == "__main__":
sensor = Melexis(fahrenheit=True)
t = sensor.readObject()
print("Object: {}ºF ({}ºF warmer than the ambient temperature)".format(
round(t, 3), round(sensor.getDifference(), 3)))
@Jimit04
Copy link

Jimit04 commented Mar 26, 2017

Thanks for the great help all.

This code works fine for me.

`

import Adafruit_GPIO.I2C as I2C

I2C.require_repeated_start()

class Melexis:

    def __init__(self, address=0x5A):
        self._i2c = I2C.Device(address,busnum=1)

    def readAmbient(self):
        return self._readTemp(0x06)

    def readObject1(self):
        return self._readTemp(0x07)

    def readObject2(self):
        return self._readTemp(0x08)

    def _readTemp(self, reg):
        temp = self._i2c.readS16(reg)
        temp = temp * .02 - 273.15
        return temp
    
#if name == "main":
sensor = Melexis()
t = sensor.readObject1()
a = sensor.readAmbient()
print("Object: {}C , Ambiant: {}C".format(round(t, 3), round(a, 3)))

`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment