#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd1(0x21,16,2);
byte board_address = 1;
byte Right[8] = {
  	0b00000,
	0b00100,
	0b00110,
  	0b11111,
  	0b00110,
  	0b00100,
  	0b00000,
  	0b00000,
};
byte x;
void setup()
{
  lcd1.init();
  lcd1.clear(); 
  lcd1.backlight(); 
  lcd1.createChar(0, Right);
  Wire.begin(1); 
}
void loop()
{ 
  //transmit to slave 2 and 3, then wait for slave response
  for(int i=2; i<4; i++){
    x=random(0, 255);
  	Wire.beginTransmission(i); // transmit to device #2
  	Wire.write(x);              // sends x 
  	Wire.endTransmission();    // stop transmitting
  	lcd1.setCursor(0,0);
  	lcd1.clear(); 
  	lcd1.print("M ");
  	lcd1.write(0);
    lcd1.write(0);
  	lcd1.print(" S");
  	lcd1.print(i);
  	lcd1.print("  ");
  	lcd1.print(x);
  	Wire.requestFrom(i, 2); //request 2 bytes from device 2 
  	lcd1.setCursor(0,1);
  	while(Wire.available()) {
  	  byte data = Wire.read(); 
  		lcd1.print("S");
  	  	lcd1.print(data); //1st byte is slave address
  		lcd1.print(" ");
      	lcd1.write(0);
      	lcd1.write(0);
  		lcd1.print(" M");
  		lcd1.print("  ");
  	  	data = Wire.read(); 
  		lcd1.print(data); //2nd byte is echo data
  	}
  	delay(500);
  }
}
---------------------------
//Slave
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
byte board_address = 2;
byte data;
void setup()
{
  Wire.begin(board_address);               
  Wire.onReceive(receiveEvent);
  Wire.onRequest(requestEvent);
}
void loop()
{
}
void receiveEvent(int n) {
  while(Wire.available()) {
    data = Wire.read(); 
  }
}
void requestEvent() {
  Wire.write(board_address);
  Wire.write(data);
}
reference:
I2C lcd

No comments:
Post a Comment