I2C hangs on Arduino Mega platform

I have a project that uses an I2C sensor and an Arduino Mega 2560 REV3. I have included the code that is running below, and this will read 16-bits from the I2C sensor and concatenate them together.

#include <Wire.h>

void readSensor(int address) {
  int c;
  int c1;
  int c2;
  //start the communication with IC with the provided address
  Wire.beginTransmission(address);
  //send a bit and ask for register zero
  Wire.write(0);
  //end transmission
  Wire.endTransmission();
  //request 1 byte from address xx
  Wire.requestFrom(address, 2);
  //wait for response
  while(Wire.available() == 0);
  //put the temperature in variable c
  c1 = Wire.read();
  c2 = Wire.read();
  c = (c1<<8) + c2;
  return c;
}

I have found that the issue occurs during the while() loop and it will sometimes get stuck on that due to what I assume is a communication issue with the sensor. This appears to be somewhat random, and if I unplug and replug the wires and restart the board sometimes it works and sometimes it does not.

I do not have an external pull up resistor and maybe that is the issue. Does anyone have experience with this and is there an alternative potential solution?

unless the sensor PCB has pull resistors 4.7Kohn is recommended
have you tried changing the I2C clock speed?

horace:
unless the sensor PCB has pull resistors 4.7Kohn is recommended
have you tried changing the I2C clock speed?

I will try adding a 4.7Kohm resistor and see if that helps.

I was not even aware that the I2C clock speed can be changed. Is this using the function Wire.setClock()? Do you have recommendations on what I should try?

use WireSetClock to set the clock

how long are the wires linking the Arduino to the sensor?

The wires are ~12 inches long.

12 inches should be OK - check if the sensor PCB has pullup resistors
I you toutch the wires does that cause corruptions?

Please remove these lines:

//wait for response
while(Wire.available() == 0);

That will not fix your problem, but you should not use those lines.
There no such thing as waiting for a response.

It seems that the I2C communication with your sensor sometimes fails.
Which sensor is it ? You may not connect a 3.3V sensor to a Arduino Mega 2560 without I2C level shifters.

Koepel:
Please remove these lines:

//wait for response

while(Wire.available() == 0);



That will not fix your problem, but you should not use those lines.
There no such thing as waiting for a response.

It seems that the I2C communication with your sensor sometimes fails.
Which sensor is it ? You may not connect a 3.3V sensor to a Arduino Mega 2560 without I2C level shifters.

Good point on the voltage, I had not considered that. Per the datasheet, the voltage on the digital IO pins is "-0.3 Vdc to 3.0 Vdc." I will wire up a level converter and see if that solves the issue. Thanks!