Browsed by
Tag: I2C

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.

How to use RS485/ RS232 / I2C cable conect (using EtherCard library)

How to use RS485/ RS232 / I2C cable conect (using EtherCard library)

Using RS485 / RS 232 / I2C cable connect you can include diferents libraries.

Ethercard library.

...
#include 
...
static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 };

...
void setup () {
   ...
   if (ether.begin(sizeof Ethernet::buffer, mymac, 53) == 0)
      Serial.println( "Failed to access Ethernet controller");
   if (!ether.dhcpSetup()) {
      Serial.println("DHCP failed");
   }
   ...

}