I have some experience with I²C (TWI) as I used it before, but it seems I can't solve this particular problem. I intend to communicate two CPUs via I²C. One is always the master and the other is the slave. I'm defining the communication protocol myself, so it's somewhat flexible, but I intend it to be as efficient as possible (i.e. the fewer bytes, the better).
I want the slave to set NACK for certain values; for instance:
MASTER = START + sends SLAVE ADDRESS SLAVE = sets ACK MASTER = sends any one "byte" command SLAVE = sets ACK or NACK depending if "byte" was a valid command or not.
The last statement is the problem, because apparently I -as the slave- have to decide for ACK or NACK before receiving the one "byte" command; i.e., in response to TWSR = 0x60 (SLA+W received). The problem is, I don't know in advance if the command will be valid or not! Apparently setting or clearing the TWEA bit is only effective for the next byte to be received.
As much as I digged into the docs, I cannot find a way to respond with NACK "on the fly" because the ATMega sets the interrupt AFTER sending the ACK (or NACK). TWSR will be either 0x80 or 0x88, which means "byte received, ACK sent" and "byte received, NACK sent" respectively.
Aside from adding padding bytes or implementing a bit-banging I²C library, is there some way to solve this?
The master controller is an NXP LPC2148, while the slave controller is an ATMega1284P.