Using one I2C bus to send two events

I have a setup with two Arduino's; one mega which function as the master and one Uno which is setup as the slave. I am transmitting two separate pieces of data both in separate functions to the slave. One piece of data is rd and the other is Temp. They each work find separately but when both are on at the same time neither work.

The sample code can be seen below.

// Include Arduino Wire library for I2C
#include <Wire.h>

// Define Slave I2C Address
#define SLAVE_ADDR 9

int VOLT = 6;
int TEMP = 9;
int rd;
int Temp;

void setup() {
pinMode(VOLT, OUTPUT);

// Initialize I2C communications as Slave
Wire.begin(SLAVE_ADDR);

// Function to run when data received from master
Wire.onReceive(receiveEvent);
Wire.onReceive(SecondRecieve);
// Setup Serial Monitor
Serial.begin(9600);

}

void receiveEvent() {
rd=Wire.read();
Serial.println(rd);
switch (rd){
case 1:
Serial.println("The cook mode Selected is bake");
analogWrite(VOLT,83);//108
break;
case 2:
Serial.println("The cook mode selected is fry");
analogWrite(VOLT,108);//151
break;
case 3:
Serial.println("The cook mode selected is sear");
analogWrite(VOLT,165);//218
break;
}

}

void SecondRecieve(){
Temp=Wire.read();
Serial.println(Temp);
if ( Temp < 200){
analogWrite(TEMP, 84);
}//first if

else if (Temp > 200 && Temp <= 250){
analogWrite(TEMP, 95);
}

else if (Temp > 250 && Temp <= 300){
analogWrite(TEMP, 105);
}

else if (Temp > 300 && Temp <= 350){
analogWrite(TEMP, 115);
}

else if (Temp > 350 && Temp <= 400){
analogWrite(TEMP, 125);
}

else if (Temp > 400 && Temp <= 450){
analogWrite(TEMP, 135);
}
else if (Temp > 350 && Temp <= 400){
analogWrite(TEMP, 125);
}
else if (Temp > 400 && Temp <= 450){
analogWrite(TEMP, 135);
}
else if (Temp > 450 && Temp <= 500){
analogWrite(TEMP, 145);
}
else if (Temp > 500 && Temp <= 550){
analogWrite(TEMP, 155);
}
else if (Temp > 550 && Temp <= 600){
analogWrite(TEMP, 166);
}
else {
analogWrite(Temp, 0);
}

}//secondRecieve

void loop() {

// Time delay in loop
delay(500);
}

You can only have one onReceive callback. The master is going to have to send something more than a number in order for the slave to know what to do with that number.

I think that receiveEvent() is an interrupt context under which you are not supposed to execute print() and analogWrite() methods which need interrupt structure to work. Set flag in the onReceive() function and based on the flag, do your other jobs in the loop() function.

Lines 66 - 72 are identical to lines 73 - 78, I wonder why?

  else if (Temp > 350 && Temp <= 400){
    analogWrite(TEMP, 125);
  }

  else if (Temp > 400 && Temp <= 450){
    analogWrite(TEMP, 135);
  }
  else if (Temp > 350 && Temp <= 400){
    analogWrite(TEMP, 125);
  }
  else if (Temp > 400 && Temp <= 450){
    analogWrite(TEMP, 135);
  }