Creating Master&Slave - I2C bus
Objective:
Here we will learn how to establish a I2C bus serial communication between 2 Arduinos. One will be Master and another will be Slave.
Theory:
Before we go for coding, we must know the basics of I2C bus and how it works. I highly recommend you to go through Scott Campbell's article on I2C bus to understand it better.
Hardware Setup:
Full Code:
ArduinoA (Master)
#include<Wire.h> //the main library
void setup()
{
Wire.begin(); //only for master to create communication
Serial.begin(9600); //MCU & Serial Monitor communication starts
}
void loop()
{
byte n = Wire.requestFrom(0x52, 1);
if ( n >0 )
{
Serial.println("Salve found");
}
}
ArduinoB (Slave)
#include<Wire.h>
void setup()
{
Wire.begin(0x52); //slave address to call by Master
Serial.begin(9600); //MCU & Serial Monitor communication starts
Wire.onRequest(sendData);
}
void loop()
{
;
}
void sendData()
{
;
}
Code Explanation:
At Master
byte n = Wire.requestFrom(0x52, 1);
Requesting Slave no-0x52 send 1byte data. If the slave 0x52 is online on the bus, then n=1, not necessary any data to come. This value "1" is used to allocate memory space for incoming data.
byte n = Wire.requestFrom(0x52, 5);
Here n=5. Which means the Master allocated 5 bytes of data where incoming data will be stored. Now if 2/3 bytes data comes then the rest of the memory location will be auto-filled with 0xFF (in decimal = 255)
At Slave
Wire.onRequest(sendData);
When the Master asks to send any data by terminating "Wire.requestFrom(0x52, 1)" in the Master side code, the "sendData" function will run automatically to send the requested data. This function works only for Slaves. Masters dont have this type of sending function. "sendData" is a regular function name, it can be replaced by any name that follows the Variable naming rules.
Result:
Master's Serial Monitor
See More Examples:
Kommentare