Hi all,
I hope someone can help me out here. I'm new to i2c and having difficulty.
I am using the Arduino (Mega) as a slave device for i2c. It is running motors, with encoders, on a wheeled robot. The "brains" of the robot are provided by a raspberry pi. The pi needs to send wheel commands and read encoder values, so communication has to be bidirectional. I know there are other ways to do this, but i2c ought to work, and I've started down that road, so I'm committed.
Before getting to the robot navigation part, I just wanted to be able to send and receive data between the pi and the Arduino as master and slave respectively, so I set up test programs. Here's the Arduino side of things.
void setup()
{
// put your setup code here, to run once:
Serial.begin(9600);
Wire.begin(SLAVE_ADDRESS); //Slave address is 0x04
Wire.onReceive(receiveData);
Wire.onRequest(sendData);
Serial.println("Ready!");
}
void loop() {
// put your main code here, to run repeatedly:
//This program does absolutely nothing except communicate over i2c
delay(100);
}
void sendData()
{byte inbuffer[4]={2,3,4,5};
Wire.write(inbuffer,4);
Serial.println("sent");
}
void receiveData(int byteCount)
{byte inbuffer[6]={0};
int index=0;
while(Wire.available())
{
//inbuffer[index]=Wire.read(); I was reading into a buffer, but I've commented out
Serial.println(Wire.read()); //I'm just printing for debugging instead of the buffer.
index++;
}
Serial.println("done");
Serial.println(index);
Serial.println(byteCount);
}
Over on the raspberry pi side, I have a program that simply ships an array of data.
The stripped down python code goes like this: (miscellaneous elements removed. Just the important part)
bus=smbus.SMBus(1)
outdata=[10,11,1,254,0,7] //arbitrary data. Just to see if it is received.
bus.write_i2c_block_data(0x04,0,outdata);
When I run the program, I get this on the pi side. (I'm going to add c style // comments for clarity.)
0 //This is the extra leading zero
10 //This is the start of the real data
11
1
254
0
7
done //The loop exited after reading/printing seven times
7 //Final index value
7 //bytecount sent to receiveData function
I've done a whole lot of variations on this. I've used even numbers of data and odd numbers of data. There is always one extra data byte available. It always arrives before the other bytes. The value is always 0. If I take out the println statements and read into a buffer, the buffer always has one extra zero in position zero, followed by the rest of the data.
I'm confident my electrical setup is ok, because some of the data arrives, and because in some variations I use the pi to request four bytes of data from the Arduino, and the pi always receives 2,3,4,5, from the Arduino, as shown in the sendData function.
Sadly, I don't have access to a logic analyzer or protocol sniffer to see the actual wire levels.
Any help would be greatly appreciated.