////////////////////////////////////////////////////////////////////////////////
// Name:       RO-052   Temperature sensor IR MLX90614                        //
// http://robotigs.com/robotigs/includes/parts_header.php?idpart=256          //
// Platform:   Arduino Uno Rev3                                               //
// Created by: HARB rboek2@gmail.com september 2017 GPL copyrights            //
// Thanks to:  https://github.com/wilson-elechouse                            //
// https://github.com/elechouse/MLX90614/tree/master/examples/MLX90614        //
// No pullup resistors needed if internal pullups are set                     //
////////////////////////////////////////////////////////////////////////////////


// SET PRECOMPILER OPTIONS *****************************************************
// Initialse conditional compiling, uncomment to include, comment to exclude ---
// Do comment for runtime versions
#define RS232                     //Uncomment to include Serial Monitor sections
//  #ifdef RS232     //Only include these lines if the variable has been defined

//Define precompiler variables -------------------------------------------------
// Define PINS -----------------------------------------------------------------

//Define the needed header files for the precompiler, no charge if not used ----
#include <i2cmaster.h>          //Thanks to: https://github.com/wilson-elechouse

//DEFINE VARIABLES -------------------------------------------------------------
  //This converts high and low bytes together and processes temperature
  //MSB is a error bit and is ignored for temps
  //0.02 degrees per LSB (measurement resolution of the MLX90614)
  double tempFactor = 0.02; 
  double tempData = 0x0000;                                  //Zero out the data
  int frac;                                        //Data past the decimal point
  bool ledBinVal   = LOW;           //Choose HIGH=on or LOW=off for on-board LED
  int dev = 0x5A<<1;                                        //Set dewvice number
  int data_low = 0;                                 //Set read value low to zero
  int data_high = 0;                               //Set read value high to zero
  int pec = 0;                                //Set temporarily variable to zero
//END OF PRECOMPILER OPTIONS ---------------------------------------------------


void setup() { //Setup runs once ***********************************************
  disable_jtag();              //Disable jtag to free port C, enabled by default
  Serial.begin(9600);   //Nothing more needed for the Serial Monitor to function
  pinMode(LED_BUILTIN, OUTPUT);          //Arduino boards contain an onboard LED
  digitalWrite(LED_BUILTIN, ledBinVal);//Onboard LED switched to default setting
  i2c_init();                                           //Initialise the i2c bus
  PORTC = (1 << PORTC4) | (1 << PORTC5);//Enable pullups only if not in hardware
}//--(end setup )---------------------------------------------------------------


void loop() { //KEEP ON RUNNING THIS LOOP FOREVER ******************************
  i2c_start_wait(dev+I2C_WRITE);           //Start I2C bus and become the master
  i2c_write(0x07);                             //Address the tempertature sensor
    
  i2c_rep_start(dev+I2C_READ);            //Restart the bus and prep[air to read
  data_low = i2c_readAck();                      //Read 1 byte and then send ack
  data_high = i2c_readAck();                     //Read 1 byte and then send ack
  pec = i2c_readNak();         //Send Nack to stop communication with the sensor
  i2c_stop();                          //Free the I2C bus for other applications
 
  // This masks off the error bit of the high byte,
  // then moves it left 8 bits and adds the low byte.
  tempData = (double)(((data_high & 0x007F) << 8) + data_low);
  tempData = (tempData * tempFactor)-0.01;
    
  float celcius = tempData - 273.15;
  float fahrenheit = (celcius*1.8) + 32;

  Serial.print("Celcius:");
  Serial.print(celcius);

  Serial.print("  Fahrenheit:");
  Serial.println(fahrenheit);

  toggle_ledBin();                  //Toggles the default on-board LED on or off
  delay(1000);                            // wait a second before printing again
} //End of void loop()                       //KEEP ON RUNNING THIS LOOP FOREVER


void toggle_ledBin(void) { //Toggles the default on-board LED on or off ********
  ledBinVal = !ledBinVal;                                         //Toggle value
  digitalWrite(LED_BUILTIN, ledBinVal);         //Set Arduino boards onboard LED
} //Exit toggle_ledBin ---------------------------------------------------------


////////////////////////////////////////////////////////////////////////////////
// PIN ALLOCATIONS TABLE ARDUINO UNO                                          //
// Board -Atmel- PIN - IDE - Function          - Connection               ALT //
//                                                                            //
// CONNECTIONS RAILS TOP LEFT: DIGITAL PWM<~> ******************************* //
// SCL   -  28 - PC5 -19/A5- ADC5/SCL/PCINT13  - MLX90614 IR temp sensor  TWI //
// SDA   -  27 - PC4 -18/A4- ADC4/SDA/PCINT12  - MLX90614 IR temp sensor  TWI //
// AREF  -  21 - REF -     - AREF              -                              //
// GND   -  22 - GND -     - GND               -                              //
// 13    -  19 - PB5 -  13 - SCK/PCINT5        - LED_BUILTIN Arduino      SPI //
// 12    -  18 - PB4 -  12 - MISO/PCINT4       -                          SPI //
// ~11   -  17 - PB3 -  11 - MOSI/OC2A/PCINT3  -                          PWM //
// ~10   -  16 - PB2 -  10 - SS/OC1B/PCINT2    -                          PWM //
// ~9    -  15 - PB1 -   9 - OC1A/PCINT1       -                          PWM //
// 8     -  14 - PB0 -   8 - PCINT0/CLK0/ICP1  -                          DIO //
//                                                                            //
// CONNECTIONS RAILS TOP RIGHT: DIGITAL PWM<~> ****************************** //
// 7     -  13 - PD7 -   7 - PCINT23/AIN1      -                          DIO //
// ~6    -  12 - PD6 -   6 - PCINT22/OCA0/AIN0 -                          PWM //
// ~5    -  11 - PD5 -   5 - PCINT21/OC0B/T1   -                          PWM //
// ~4    -   6 - PD4 -   4 - PCINT20/XCK/T0    -                          PWM //
// ~3    -   5 - PD3 -   3 - PCINT19/OC2B/INT1 -                          INT //
// ~2    -   4 - PD2 -   2 - PCINT18/INT0      -                          INT //
// TX->1 -   3 - PD1 -   1 - PCINT17/TXD       - Serial monitor           TXD //
// RX<-0 -   2 - PD0 -   0 - PCINT16/RCD       - Serial Monitor           RCD //
//                                                                            //
// CONNECTIONS RAILS BOTTOM LEFT: POWER ************************************* //
// 5V    -   7 - VCC -      - VCC              -                          VCC //
// RES   -   1 - RES -      - PCINT14/RESET    -                          RES //
// 3.3V  -     -     -     -                   -                              //
// 5V    -     -     -     -                   - Connected to breadboard      //
// GND   -     -     -     -                   - Connected to breadboard      //
// GND   -     -     -     -                   -                              //
// Vin   -     -     -     -                   -                              //
//                                                                            //
// CONNECTIONS RAILS BOTTOM RIGHT: ANALOG IN ******************************** //
// A0    -  23 - PC0 -A0/14- ADC0/PCINT8       -                          ADC //
// A1    -  24 - PC1 -A1/15- ADC1/PCINT9       -                          ADC //
// A2    -  25 - PC2 -A2/16- ADC2/PCINT10      -                          ADC //
// A3    -  26 - PC3 -A3/17- ADC3/PCINT12      -                          ADC //
// A4    -  27 - PC4 -A4/18- ADC4/SDA/PCINT12  -                          TWI //
// A5    -  28 - PC5 -A5/19- ADC5/SCL/PCINT13  -                          TWI //
////////////////////////////////////////////////////////////////////////////////
// EEPROM MEMORY MAP in 8 bits bytes:                                         //
// Start End  Number Description                                              //
// 0000  0000      1 Never use this memory location to be AVR compatible      //
////////////////////////////////////////////////////////////////////////////////
//345678911234567892123456789312345678941234567895123456789612345678971234567898
////////////////////////////////////////////////////////////////////////////////
// FUSES (can always be altered by using the STK500)                          //
// On-Chip Debug Enabled: off                            (OCDEN=0)            //
// JTAG Interface Enabled: off                           (JTAGEN=0)           //
// Preserve EEPROM mem through the Chip Erase cycle: On  (EESAVE = 0)         //
// Boot Flash section = 2048 words, Boot startaddr=$3800 (BOOTSZ=00)          //
// Boot Reset vector Enabled, default address=$0000      (BOOTSTR=0)          //
// CKOPT fuse (operation dependent of CKSEL fuses        (CKOPT=0)            //
// Brown-out detection level at VCC=2,7V;                (BODLEVEL=1)         //
// Ext. Cr/Res High Freq.; Start-up time: 16K CK + 64 ms (CKSEL=1111 SUT=11)  //
// LOCKBITS (are dangerous to change, since they cannot be reset)             //
// Mode 1: No memory lock features enabled                                    //
// Application Protect Mode 1: No lock on SPM and LPM in Application Section  //
// Boot Loader Protect Mode 1: No lock on SPM and LPM in Boot Loader Section  //
////////////////////////////////////////////////////////////////////////////////

void disable_jtag(void) { //Disable jtag to free port C, enabled by default ****
#if defined(JTD)                           //Not all AVR controller include jtag
  MCUCR |= ( 1 << JTD );                                //Write twice to disable
  MCUCR |= ( 1 << JTD );                                       //So stutter once
#endif                                            //End of conditional compiling
} //Exit jtag_disable ----------------------------------------------------------