Project 1 - Interfacing a 16*2 LCD with Arduino using I2C protocol
//MASTER CODE
#include<Wire.h> //Library for I2C Communication functions
#include<LiquidCrystal.h> //Library for LCD display function
LiquidCrystal lcd(12, 11, 5, 4, 3, 2); //Define LCD Module Pins (RS,EN,D4,D5,D6,D7)
char Mreceive[10];//String to RECEIVE the message
char Msend[9];//String to SEND the message
void setup()
{
Serial.begin(9600);//To begin serial comm at baud rate 9600
Wire.begin(); //To begin I2C communication
lcd.begin(16,2);//To begin LCD
lcd.clear();
}
void loop()
{
Wire.requestFrom(8,9);// request 9 characters from slave arduino (8-address)
lcd.setCursor(0,0);//Sets Currsor at line1 of LCD
lcd.print("MASTER");//print master on masters LCD
delay(1000);
lcd.setCursor(0,1);//Sets Currsor at line2 of LCD
int i=0;
while(0<Wire.available()) //To check the number of bytes available
{
Mreceive[i]=Wire.read(); //To print character by character
i++;
}
lcd.print(Mreceive); //Prints MasterReceive in LCD received from Slave
delay(1000);
Wire.end();
char Msend[9] = "HI-SLAVE";//sending data to slave
Wire.beginTransmission(8);// start transmit to slave arduino (8)
Wire.write(Msend); // sends data to slave
Wire.endTransmission(); // stop transmitting
}
//SLAVE PROGRAM
#include<Wire.h> //Library for I2C Communication functions
#include<LiquidCrystal.h> //Library for LCD display function
LiquidCrystal lcd(12, 11, 5, 4, 3, 2); //Define LCD Module Pins (RS,EN,D4,D5,D6,D7)
char Slreceived[10];//INITIALIZING THE RECEIVING VARIABLE AS STRING
void setup()
{
Serial.begin(9600);//SERIAL COMM AT BAUD RATE 9600
Wire.begin(8); //TO BEGIN I2C COMM
Wire.onRequest(send);//FUNCTION CALL WHEN MASTER REQ DATA FROM SLAVE
Wire.onReceive(receive);//FUNCTION CALL WHEN SLAVE RECEIVES DATA FROM MASTER
lcd.begin(16,2);//TO BEGIN LCD
lcd.clear();
}
void loop(void)
{
lcd.setCursor(0,0);//Sets Currsor at line1 of LCD
lcd.print("SLAVE");//PRINT SLAVE ON LCD
lcd.setCursor(0,1);//Sets Currsor at line2 of LCD
lcd.print(Slreceived);//Prints MasterReceive in LCD received from Master
delay(1000);
}
void receive(int k)
{
int i=0;
while(0<Wire.available()) //To check the number of bytes available
{
Slreceived[i]=Wire.read(); //To print character by character
i++;
}
Wire.end();
}
void send() //This Function is called when Master wants DATA from slave
{
char SlaveSend[10] = "HI-MASTER";
Wire.write(SlaveSend);
}