The code is a mess. The receiveEvent() function is called from an ISR. You can’t do Serial.println() inside it. You also must keep it as short as possible. Variables shared between loop() and ISR must be volatile. And, accesses to them in loop() must be protected from interrupts. It also looks like your loop() function will get stuck in an infinite ‘while’ loop. See below for a possible framework to build on. Make the code in your loop() function non-blocking.
EDIT: Simplified the Code:
#include <Wire.h>
volatile int sensor;
volatile boolean newFlag = false;
void setup() {
Wire.onReceive(receiveEvent); // what to do when receiving data
Serial.begin(9600); // start serial for output
}
void loop() {
int localSensor;
if (newFlag) {
noInterrupts();
localSensor = sensor;
newFlag = false;
interrupts();
/*
******* Process new localSensor value here. Only use NON-BLOCKING code *******
*/
}
}
void receiveEvent(int HowMany) {
sensor = Wire.read(); // read the first byte
while (Wire.available()) {
(void)(Wire.read()); // flush the rest (if any)
}
newFlag = true;
}