// Melexis_1 (Arduino - ATMega328)
//
// Arduino                      Melexis MLX90614
//
// 9 (PORTB.1) ----------------- SDA (2)
// 8 (PORTB.0) ----------------- SCL (1)
//                       +5 ---- VDD (3)
//                       GRD --- VSS (4)
//
// Continually measures ambient Ta and object To and displays values
// in degrees F to terminal.
//
// copyright, Peter H Anderson, Baltimore, MD, Jan 11, '11
//
// improve description
// improve on I2CInByte, reading a specific bit
// CRC calculation

#include <avr\io.h>

#define cbi(sfr, bit) (sfr &= (~(0x01<<bit)))
#define sbi(sfr, bit) (sfr |= (0x01 << bit))

#define TRUE 1
#define FALSE 0

#define SCL 0
#define SDA 1  

float meas_temperature(byte slave_address, byte ram_location);
float celcius_to_fahr(byte Tc);

void I2CStart(void);
void I2CStop(void);
void I2COutByte(byte X);
byte I2CInByte(byte Ack);

byte CalcCRC8(CRC8, v);


void SDA_HIGH(void);
void SCL_HIGH(void);
void SDA_LOW(void);
void SCL_LOW(void);

void print_float(float f, int num_digits);

void setup(void)
{
  
   Serial.begin(9600);
   delay(5000);
   Serial.println(">>>>>>>>>>>>>>>>>>>>>>>>");  // just to be sure things are working
}

void loop(void)
{

       float Ta_f, To_f;
     
       meas_temperature(&Ta_f, 0x00, 0x06);
       meas_temperature(&To_f, 0x00, 0x07);
       
       print_float(Ta_f, 2);
       Serial.print("     ");
       
       print_float(To_f, 2);
       Serial.print("\n");
                   
       delay(1000);             
}
    
byte meas_temperature(float *pT, byte slave_address, byte ram_location)  // 0x06 for Ta, 0x07 for Tobj
{
       byte low, high, PEC, CRC8;
       unsigned int v;
       float Tc, Tf;
     
       I2CStart();
       I2COutByte(slave_address); 
       I2COutByte(ram_location); 
       
       I2CStart();
       I2COutByte(slave_address | 0x01);
       low = I2CInByte(1);
       high = I2CInByte(1);
       PEC = I2CInByte(1);
       I2CStop();
     
       CRC8 = 0x00;
       CRC8 = CalcCRC8(CRC8, low);
       CRC8 = CalcCRC8(CRC8, high);
       CRC8 = CalcCRC8(CRC8, PEC);
       
       if (CRC8 != 0)
       {
          *pT = 99.9; // used as failure indication
          return(FAILURE);
       }
       
       v = (unsigned int) high * 256 + low;
       
       Tc = (float)(v) * 0.02 - 273.15;
       Tf = 1.8 * Tc + 32.0;
       *pT = Tf;
       return(SUCCESS);
}

// The implemetation of the complete code including the implementations of all 
// functions will be included with your order.