/********************************************************
*  Code to use the thermopile array to track the hottest
*  object in a room. The thermopile array must be attached
*  to a servo.
*  By: Jonathan Mash
*  Date: Feb. 2009
*********************************************************/
 
#include <Wire.h>
#include <Servo.h> 
 
bool DEBUG = true; //Degug flag
Servo myservo;   
int pos = 90;    // variable to store the servo position 
byte sensor_address = 0xd0;
byte heat[9];
 
void setup() 
{ 
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object 
  Wire.begin();
  Serial.begin(9600);
} 
 
 
void loop() 
{ 
   int i;
   int idxHigh=0;
   byte valHigh=0;
   if(DEBUG) Serial.print(sensor_address, HEX);
   if(DEBUG) Serial.print(": ");
 
   getHeat();
 
   for(i = 1; i<9; i++)
   {
     heat[i]-=heat[0];
     if(heat[i] > 100)
       heat[i] = 0;
 
     if(heat[i] > valHigh)
     {
       idxHigh = i;
       valHigh = heat[i];
     }
 
     if(DEBUG) Serial.print(heat[i], DEC);
     if(DEBUG) Serial.print(" ");
   }
 
   if(valHigh > 4)
   {
      pos = pos - (idxHigh-4);
      if(pos > 140)
         pos = 140;
      else if (pos < 40)
         pos = 40;
   }
 
   myservo.write(pos);
   if(DEBUG) Serial.println("");
//   delay(50); 
} 
 
 
void getHeat()
{
   int i=0;
   for(i=1; i<=9; i++)
   {
      Wire.beginTransmission(sensor_address>>1);
      Wire.send(i);
      Wire.endTransmission();
 
      Wire.requestFrom(sensor_address>>1, (int) 1);
      while(Wire.available() < 1)
      { ; }
 
      heat[i-1] = Wire.receive(); // receive a byte as character
   } 
 
}