program for temperature reading with mlx90615

Dependencies:   crc8

Revision:
0:db513e91a2c9
Child:
2:c4552b8c47c0
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Mlx90615.cpp	Wed Jul 15 18:20:00 2020 +0000
@@ -0,0 +1,114 @@
+#include "Mlx90615.h"
+#include "smbus.h"
+
+I2C i2c(p28, p27);//I2C_SDA, I2C_SCL 
+void Mlx90615::wake()
+{
+	/*SCL = 0;
+	wait_ms(50);
+	SCL = 1;*/
+	MLX_VCC = 1;
+	wait_us(301*1000);//Waiting for valid data as datasheet says
+}
+
+unsigned int Mlx90615::sleep(){
+	MLX_VCC = 0;
+	return 1;
+}
+
+unsigned int Mlx90615::read(unsigned char memory, unsigned char address){
+	unsigned char crc, addr, status = 0;
+	unsigned int read = 0x0000;
+
+	addr = memory + address;
+	
+	i2c.start();
+
+	smbus_send_address(0x5B, WRITE);
+	if(!i2c.ACK) return 0;
+
+	smbus_send_byte(addr);
+	if(!i2c.ACK) return 0;
+
+	i2c.start();
+
+	smbus_send_address(0x5B, READ);
+	if(!i2c.ACK) return 0;
+
+	read = smbus_read_uint(&status, LITTLE_ENDIAN);	
+
+	crc = smbus_read_byte(&status);
+
+	smbus_stop();
+
+	return read;
+}
+
+unsigned int Mlx90615::read_temperature(){
+	unsigned int temp = read(RAM, 0x07);
+	while(temp == 0)
+	{
+		wait_us(5000);
+		temp = read(RAM, 0x07);
+	}
+	return temp;
+}
+
+/*float convert_to_celsius(unsigned int temperature){
+	return temperature * 0.02 - 273.15;
+}*/
+typedef unsigned char uint8_t;
+
+uint8_t gencrc(uint8_t *data, size_t len)
+{
+    uint8_t crc = 0xff;
+    size_t i, j;
+    for (i = 0; i < len; i++) {
+        crc ^= data[i];
+        for (j = 0; j < 8; j++) {
+            if ((crc & 0x80) != 0)
+                crc = (uint8_t)((crc << 1) ^ 0x31);
+            else
+                crc <<= 1;
+        }
+    }
+    return crc;
+}
+
+void Mlx90615::write(unsigned char address, unsigned int value){
+	unsigned char addr = EEPROM + address;
+	unsigned char bytes[4], crc, vh, vl;
+	vh = value >> 8;
+	vl = value;
+	bytes[0] = 0xB6;
+	bytes[1] = addr;
+	bytes[2] = vl;
+	bytes[3] = vh;
+	crc = gencrc(bytes, 4);
+
+	i2c.start();
+
+	smbus_send_address(0x5B, WRITE);
+
+	smbus_send_byte(addr);
+
+	smbus_send_byte(vl);
+
+	smbus_send_byte(vh);
+
+	smbus_send_byte(crc);
+
+	smbus_stop();
+}
+
+void Mlx90615::erase_eeprom_address(unsigned char address){
+	write(address, 0x0000);
+}
+
+void Mlx90615::set_emissivity(float e){
+	unsigned int emissivity;
+	emissivity = 16384 * e;
+	erase_eeprom_address(0x03);
+	wait_us(5*1000);
+	write(0x03, emissivity);
+}