Hi I am using an Arduino as a Slave device to communicate with a device which is on Master mode.
So ideally, WHen the master requests a read first, I write back the first 1 byte data. Following this the master again requests data, for which I reply. And then the master writes back with the value of the data stored inside the master controller.
But what happens is when I am writing from slave as response of a read request from the master, this is what I see on the Logic Analyzer (See pic attached). The written data is somehow delayed and this results the wrong data being returned when it writes back.
Previously I have encountered something similiar when i had serial print inside requestevent(). But since I dont have any in this piece of code, iam quite clueless. Please let me know if you have know why this happens.
Heres what my code looks like:
//All variables and i2c init is done before this.....
void loop()
{
if(mode_comm == true)
{
switch(data_request_count)
{
case 0: tx_buffer = 5;
if(data_tx_done == true)
{
data_request_count = 1;
data_tx_done = false;
}
break;
case 1: tx_buffer = 23;
if(data_tx_done == true)
{
data_request_count = 2;
data_tx_done = false;
}
case 2: if(data_received == true)
{
Serial.println(data_rx);
data_received = false;
mode_comm = false;
}
}
}
}
//********************************************
//Initiate i2c with the given slave address
//********************************************
void init_i2c(int slave_address)
{
Wire.begin(slave_address);
//Wire.write(199);
Wire.onReceive(receiveEvent);
Wire.onRequest(requestEvent);
delay(5);
}
//********************************************
//*********Master Write Interrupt function***********
//********************************************
void receiveEvent(int howMany)
{
if (slave == 64)
{
while (1 < Wire.available())
{
char c = Wire.read();
}
data_rx = Wire.read();
data_received = true;
}
else
{
data_rx = Wire.read();
tx_buffer = data_rx;
}
}
//********************************************
//*********Master Read Interrupt function***********
//********************************************
void requestEvent()
{
Wire.write(tx_buffer);
data_tx_done = true;
}
