I2C COMMUNICATION PROTOCOL || CONTROLLING 2 LEDS WITH BUTTONS || MASTER ...


I2C MASTER CODE:-
#include <Wire.h>
int BTN1 = 6;
int BTN2 = 7;

int BUTTON1 = 0;
int BUTTON2 = 0;


void setup()
{
  Wire.begin();
  pinMode(BTN1, INPUT);
  pinMode(BTN2, INPUT);
}

void loop()
{
//   Wire.beginTransmission(6);// TRANSMIT TO DEVICE #1
//    Wire.beginTransmission(6);// TRANSMIT TO DEVICE #2
   
   Wire.beginTransmission(6);// TRANSMIT TO DEVICE #6

   BUTTON1 = digitalRead(BTN1);
   BUTTON2 = digitalRead(BTN2);
   
   Wire.write(BUTTON1);
   Wire.write(BUTTON2);
   Wire.endTransmission();
//   delay(500);
}



I2C SLAVE CODE:-
#include <Wire.h>
int LED1=12;
int LED2=13;

int BUTTON1 =LOW;
int BUTTON2 =LOW;

void setup()
{
//  Wire.begin(1);// RECEIVE FROM device #1
//  Wire.begin(2);// RECEIVE FROM device #2
  Wire.begin(6);// RECEIVE FROM device #6
  
  Wire.onReceive(receiveEvent); 
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
}

void loop()
{
  delay(100);
}

void receiveEvent(int howMany){

BUTTON1 = Wire.read();
BUTTON2 = Wire.read();
  
  if (BUTTON1 == HIGH){
  
        digitalWrite(LED1,HIGH);
  }
  else{
        digitalWrite(LED1,LOW);
  }

    if (BUTTON2 == HIGH){
  
        digitalWrite(LED2,HIGH);
  }
  else{
        digitalWrite(LED2,LOW);
  }
}


Post a Comment

0 Comments