Hi All,
I'm having some trouble communicating via I2C between 2 ATmega328s.
Here is the setup:
I have 2 ATmega328 chips. I assign one the address 0x0a and the other 0x0b.
I can send commands from either chip to the other without any problems. However, what I need to do is when a command is received, the chip needs to send a response. This is where it falls over. Through debugging, I can see this is the flow:
0x0b sends command "requestID" to 0x0a
0x0a receives "requestID" and tries to send "id1" back to 0x0b
This is where it stops. 0x0b never receives anything back. And it seems that 0x0a never sends it. I can't even get a return code from Wire.endTransmission() on 0x0a - it seems to crash on the endTransmission().
I've tried reversing the roles of each chip to rule out a faulty chip, but I have the same problem. As mentioned, I can send multiple commands and they are all received OK, but as soon as I try to send a response back after receiving a command it crashes. I have tried adding in delays between sending and receiving, but no luck.
A4 is connected to A4, and A5 to A5, both chips share the same ground. These are the only two devices on the bus. I have tried with and without pullup resistors. Any help?
Here is my code on device 0x0a:
#include <Wire.h>
String i2cBuffer="";
byte buffer=0x00;
void setup() {
Serial.begin(9600);
Wire.begin(0x0a);
Wire.onReceive(receiveEvent);
}
void receiveEvent(int howMany){
i2cBuffer="";
while (Wire.available() > 0){
buffer = Wire.receive();
i2cBuffer=String(i2cBuffer + buffer);
}
processBuffer(i2cBuffer);
}
void processBuffer(String processCommand) {
Serial.print("Command Received: '");
Serial.print(processCommand);
Serial.println("'");
if (processCommand=="requestID") {
sendCommand(0x0b,"id1");
}
}
void sendCommand(byte device, String command) {
char sendChar[32]="";
command.toCharArray(sendChar,32);
Serial.print("Sending '");
Serial.print(command);
Serial.print("' to Device ");
Serial.println(device,HEX);
Wire.beginTransmission(device);
Wire.send(sendChar);
int response=Wire.endTransmission();
Serial.print("Return Code: ");
Serial.println(response);
}
void loop()
{
}