I have found a few good tutorials on how to send and receive data via I2C in connected arduinos. My limitation is now how to transmit different types of data like for instance, long, float, etc. Right now the communication via I2C using the wire library only allows transmission of numbers between 0 and 255. How can one transmit different types of numbers?.
In my code a master receives three types of data from the slave, and it send data of a fourth variable to the slave.
here is the code for the master
#include <Wire.h>
const int SLAVE_ADDRESS = 8; //Slave arduino ID
int table[]={0,0,0}; //the data will be transmited via table as to allow different data to be transfer.
void setup ()
{
Wire.begin ();
Serial.begin (9600); // start serial for output
} // end of setup
void loop()
{
Wire.requestFrom(SLAVE_ADDRESS, 3);// request 3 bytes from slave device #8
for(int i=0;i<3;i++)//organizes the data from the slave in the table
{
int c = Wire.read(); // receive a byte as character
table[i]=c;
}
//displays the data
Serial.print('\n');
Serial.print(table[0]);
Serial.print('\t');
Serial.print(table[1]);
Serial.print('\t');
Serial.print(table[2]);
Serial.print('\n');
delay (500);
// transmit just this variable to the slave
int Work=1;
Wire.beginTransmission (8);
Wire.write (Work);
Wire.endTransmission ();
}
here is the code for the slave
#include <Wire.h>
int table[]={0,0,0};
int Work=0;
void setup() {
Wire.begin(8); // join i2c bus with address #8
Wire.onRequest(requestEvent); // register event
Wire.onReceive(receiveEvent); // register event
}
void loop() {
int x=120;
int y=1200;// gets converted to an strange # because is larger than 255
int z=3;
table[0]=x;
table[1]=y;
table[2]=z;
}
void requestEvent()
{
uint8_t Buffer[3];
Buffer[0]=table[0];
Buffer[1]=table[1];
Buffer[2]=table[2];
Wire.write(Buffer,3);
}
void receiveEvent(int howMany)
{Work = Wire.read();}