program for temperature reading with mlx90615

Dependencies:   crc8

Mlx90615.cpp

Committer:
glsfacom
Date:
2020-07-16
Revision:
2:c4552b8c47c0
Parent:
0:db513e91a2c9

File content as of revision 2:c4552b8c47c0:

#include "Mlx90615.h"
#include "crc8.h"

extern Serial pc;
I2C i2c(p28, p27);//I2C_SDA, I2C_SCL 

inline void 
Mlx90615::wake()
{
	/*SCL = 0;
	wait_ms(50);
	SCL = 1;*/
	MLX_VCC = 1;
	ThisThread::sleep_for(301);//Waiting for valid data as datasheet says
}

inline void 
Mlx90615::sleep(){
	MLX_VCC = 0;
}

float 
Mlx90615::read(unsigned char memory, unsigned char address){
	unsigned char crc, addr, status = 0;
	char read[2];
    int ACK = 0;

	addr = memory + address;

    read[0] = 0x01;
    read[1] = 0x00;
	
    char cmd = 0x27;
	i2c.start();
	ACK = i2c.write(0x5b<<1);
	if(!ACK) return -1;
    ACK = i2c.write(addr);
	if(!ACK) return -1;
	i2c.start();
    ACK = i2c.write((0x5b<<1)|1);
	if(!ACK) return -1;
    read[0] = i2c.read(ACK);
    if(!ACK) return -1;
    read[1] = i2c.read(ACK);
    i2c.read(ACK);
	float temp = (float((read[1] << 8) | read[0]));
	return temp*0.02-273.15;
}

float 
Mlx90615::read_temperature(){
	float temp = read(RAM, 0x07);
    int cont = 0;
	while(temp == 0)
	{
        if(cont == 100)
        {
            pc.printf("got 100 times 0\n");
            cont = 0;
        }
		wait_us(5000);
		temp = read(RAM, 0x07);
        cont++;
	}
	return temp;
}

void 
Mlx90615::write(unsigned char address, unsigned int value){
	unsigned char addr = EEPROM + address;
	char *bytes;
    unsigned char crc, vh, vl;
	vh = value >> 8;
	vl = value;
	bytes[0] = 0xB6;
	bytes[1] = addr;
	bytes[2] = vl;
	bytes[3] = vh;
	crc = crc8(bytes, 4);

    i2c.start();
    i2c.write(0x5b<<1);
	i2c.write(addr);
	i2c.write(vl);
    i2c.write(vh);
	i2c.write(crc);
    i2c.stop();
}

inline void 
Mlx90615::erase_eeprom_address(unsigned char address){
	Mlx90615::write(address, 0x0000);
}

void 
Mlx90615::set_emissivity(float e){
	unsigned int emissivity;
	emissivity = 16384 * e;
	erase_eeprom_address(0x03);
	ThisThread::sleep_for(5);
	Mlx90615::write(0x03, emissivity);
}