I2C Communication

I2C Communication

In order to communicate through I2C, we have to do two type of programs. We have to create some code for the Master device (PLC in our case), and another piece of code for the Slave devices, such as PLC, or any other device (RTC clock, ADC,…, that has an I2C available port).

Master Code:

#include <Wire.h>
void setup()
{
  Wire.begin();

  Serial.begin(9600); 
  delay(500);
}
void loop()
{
  Serial.println("Initial");

  Wire.requestFrom(2, 1);  // request 1 byte from device #2 
  while(Wire.available())  { 
    char c = Wire.read();
    Serial.println(c);
  } 
  delay(100) ;
}

Slave code:

#include <Wire.h>

void setup()
{
  Wire.begin(2);                // join i2c with the device #2
  Wire.onRequest(requestEvent);
}

void loop(){
  delay(100);
}

void requestEvent()
{
  Wire.write("k"); // respond with 1-byte-message
}                       

This is a minimum code to communicate through I2C. In this case we have a Master PLC that asks for a character. The Master asks Slave (#2). When Slave receives the request, respond with one “k” letter. We will see all of them through the RS232 console.

2 thoughts on “I2C Communication

  1. Hello Amit, I am currently wonrikg on a project for my university, and I need to be able to connect on the schools network with an arduino through wireless. So i need DHCP support, do you have any recommendations ?thank you

Comments are closed.

Comments are closed.