 
 SoftwareSerial display(8, 9);
 
-int ledPin = 13;
 int mphonePin = 0;
-int buzzPin = 12;
+int buzzPin = 10;
 int cycle = 0, vol = 0;
-double temp = 0;
-boolean flash = false;
+double temp = 0, ref = 0;
+boolean flash = false, sample = false, alarm = false, buzz = LOW;
 
 void setup(){
   Serial.begin(9600);

  display.write('e');
  display.write('s');
  display.write('t');
  display.write(0x77);
  display.write(0b00010000);
  
  i2c_init(); //Initialise the i2c bus
  PORTC = (1 << PORTC4) | (1 << PORTC5);//enable pullups

  //pinMode(ledPin, OUTPUT);
  pinMode(mphonePin, INPUT);
  pinMode(buzzPin, OUTPUT);
}

float readTemp(){

  return maxR-minR;
}

void loop() {
  if (sample) {
    ref = readTemp();
    int tv = readVol();
    if (ref > temp)
      temp = ref;
    if (tv > vol)
      vol = tv;
    cycle++;
    if (cycle == 60) {
      cycle = 0;
      if (Serial) {
        Serial.print(temp);
        Serial.print(" ");
        Serial.println(vol);
      }
      temp = 0;
      vol = 0;
    }
  } else {
    
    if (alarm && readTemp() <= ref + 5)
      cycle++;
    else if (!alarm && readTemp() > ref + 5)
      cycle++;
    else
      cycle = 0;
    if (cycle > 10) {
      if (alarm)
        alarm = false;
      else
        sample = true;
      cycle = 0;
    }
  } 
  
  if (alarm || buzz) {
    buzz = !buzz;
    digitalWrite(buzzPin, buzz);
  }
  
  flash = !flash;
  display.write(0x77);
  display.write(flash << 4 | sample << 3 | alarm | alarm << 1 | alarm << 2 | alarm << 3);
  
  delay(1000); // wait a second before printing again
}
