@chucktodd
You were right. I did not declare temp as volatile. I will change that. Unfortunately I am not able to check if it works now right away, but for sure I will let you know tomorrow as soon as I implement this.
About my code. Well, the project is a bit more complicated than I described it earlier.
I just wanted to know the answer to the basics so I could go on with the rest myself, but if you asked - the communication looks like this (or at least I understand it that way):
-
Master sends one byte (write mode): It sends the number (address) of value which it wants to obtain from Arduino.
Master requests data (read mode): It wants to receive a value of previously sent address.
-
Master sends two bytes (write mode): First byte - address to which he wants to write data. Second one - the data.
The whole code I wrote (with variables changed to volatile):
#include <EEPROM.h>
#include <Wire.h>
volatile uint8_t temp, temp2;
volatile uint8_t eeprom[1000]; // Data to emulate EEPROM, which is too slow for I2C
void setup(){
Wire.begin((0xA << 3 | 0x0));
Wire.onReceive(receiveEvent);
Wire.onRequest(requestEvent);
// Loading EEPROM values to volatile variables
for (int i=0; i<1000; i++){
eeprom[ i ]=EEPROM[ i ];
}
}
void loop(){
}
// Master asks for: access to register bit - sends 1 bit / writing data to this bit - sends 2 bits
void receiveEvent(int howMany){
if (Wire.available())
{
// First bit = register bit
temp = Wire.read();
}
if (Wire.available())
{
// Second bit (if exists) - data bit to be written to EEPROM[temp]
eeprom[temp] = Wire.read();
// Saving received data to EEPROM as well (I need it after shutdown)
EEPROM[temp] = eeprom[temp];
}
}
// Master requests data from the last called register - temp
void requestEvent(){
Wire.write(eeprom[temp]);
}
@Peter_n
Yes, its the one.
About the program in the post you pasted:
I did actually run it a week ago, but it was not really of use. For my project I need to emulate the chip, not to exchange data with it. But running it at least gave me some kind of idea of communication and was a real help.
About your P.S:
Well I know it, but i wanted to collect certain data depending on how many bytes master sends. My previous problem was a bit shortened, because I did not want to waste your time. You are probably right and as I am new to the I2C communication I am making such pointless mistakes. Thank you for pointing it to me. Any kind of help is appreciated as I want to learn more
Huge thanks for your help
I will let you know if it worked.