I am working on a project which requires communication from an Arduino Due (Master) and an FDC2214Q1 C to D IC (Slave), but there is some variability as to whether the code works or not depending on seemingly random variables.
I have narrowed the issue to the function I am using to read 2 bytes from the slave. The code is pretty standard, and is as follows:
// Read 2 byte from the FDC at 'address'
uint16_t FDC2214::read16FDC(uint16_t address) {
uint16_t data;
Wire.beginTransmission(_i2caddr);
Wire.write(address);
Wire.endTransmission(false); //restart
Wire.requestFrom(_i2caddr, (uint8_t) 2);
while (!Wire.available());
data = Wire.read();
data <<= 8;
while (!Wire.available());
data |= Wire.read();
Wire.endTransmission(true); //end
return data;
}
The code seems to get hung up sometimes on while (!Wire.available()) and if I simply remove that step, I never get the correct Device ID.
However, if I simply unplug the DUE and close the Serial Monitor and replug in and upload, it works. I just kind of upload and disconnect a few times and open and close the Serial Monitor and sometimes it works great, other times it gets hung up?
Any ideas what could be causing such and issue?
Code based on this library: https://github.com/zharijs/FDC2214/blob/master/src/FDC2214.cpp
Final code that has been working, removes need for While loop:
uint16_t FDC2214::read16FDC(uint16_t address) {
uint16_t data;
Wire.beginTransmission(_i2caddr); //queuing the slave address
Wire.write(address); //queuing the register address/pointing regsiter
byte busStatus = Wire.endTransmission(); //transmit all queued data and bring STOP condition on I2C Bus
if(busStatus != 0x00)
{
Serial.print("Transmission Error....!");//transmissiion error wait here for ever
while(1);
}
Wire.requestFrom(_i2caddr, (uint8_t) 2); //this is looping code; when 2-byte has arrived, the loop terminates
data = Wire.read(); //read the first byte from FIFO Buffer
data = (data <<8)| Wire.read(); //16-bit data is formed
Wire.endTransmission(true); //end
return data;
}
while
commands should not be indented ... the indentation implies that the two commands are inside thewhile loop
.... they are not part of the while loop