It is working! I reviewed the code using in the correct way the "volatile" keyword and avoiding the use of serial object in the interrupt methods. So the final code if can be useful for others:
#include <Wire.h>
#define slaveAddress 0x08
#define INTERUPT_PIN 4
volatile byte command = 0;
volatile byte txTable[4]; //for sending data over I2C
volatile byte rxTable[4]; //for sending data over I2C
volatile bool newDataAvailable;
void setup()
{
Serial.begin(9600);
Serial.println("Setup...");
newDataAvailable = false;
Wire.begin(slaveAddress); //I2C slave address
//Wire activates the internal pull-up resistors, let's deactivate them
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega8__) || defined(__AVR_ATmega328P__)
// deactivate internal pull-ups for twi
// as per note from atmega8 manual pg167
cbi(PORTC, 4);
cbi(PORTC, 5);
#else
// deactivate internal pull-ups for twi
// as per note from atmega128 manual pg204
cbi(PORTD, 0);
cbi(PORTD, 1);
#endif
Wire.onReceive(i2cReceive); //register handler onReceive
Wire.onRequest(i2cTransmit); //register handler onRequest
Serial.println("...end.");
}//setup
void i2cReceive(int byteCount) {
if (byteCount == 0)
return;
// Commands in range 0x000-0x7F (0-127) are writes TO this slave, and expects nothing in return.
// Commands in range 0x80-0xFF (128-255) are reads, requesting data FROM this device
command = Wire.read();
if (command < 0x80) {
i2cHandleRx(command);
}
}
void i2cTransmit() {
//called by event
byte numBytes = 0;
switch (command) {
case 0x90:
numBytes = 4;
break;
}
if (numBytes = 4) {
Wire.write((byte*)txTable, numBytes);
}
//put down the interupt signal
digitalWrite(INTERUPT_PIN, LOW);
}
byte i2cHandleRx(byte command) {
// The I2C Master has sent data, store them in receiving buffer
byte result = 0;
switch (command) {
case 0x0A:
if (Wire.available() == 4)
{
for (int i = 3; i >= 0; i--)
rxTable[3-i] = Wire.read();
result = 4;
}
break;
}
if (result != 0)
newDataAvailable = true; //let's say we have new data available and leave the receiving process
return result;
}
In the code are missing some parts, like where I store or retrieve data from buffers or where I handle the start of transmission to the master.
Thank you very much for your help! ![]()