Project 1 - Interfacing a 16*2 LCD with Arduino using I2C protocol
//master code
#include <Wire.h> // library for I2C communication
void setup()
{
Wire.begin(); //initializing the I2C communication
Serial.begin(9600);
}
void loop()
{
int potvalue = analogRead(A0); //storing the analog value
byte MasterSend = map(potvalue, 0, 1023, 0, 127); //mapping the potentiometer value from (0-1023) to (0-127)
Wire.beginTransmission(8); //start th transmission
Wire.write(MasterSend); //sending the value to slave
Wire.endTransmission(); //ending the transmission
Serial.println("I2C communication"); //printing on serial monitor
Serial.println("Data is sent to slave");
delay(500);
}
//slave code
#include <Wire.h> //library for I2C communication
#include <LiquidCrystal.h> //library for LCD
LiquidCrystal lcd(12,11,5,4,3,2); //initializing the LCD pins
int slaveReceived = 0; //global variable to store master data
void setup()
{
Serial.begin(9600); //to begin serial communitcation at baud rate 9600
lcd.begin(16,2); //settinG up the number of columns and rows of the LCD
Wire.begin(8); //Initializing the I2C communication
Wire.onReceive(receiveEvent); //function call on receiving the data from master
//lcd.setCursor(0, 0); // Set the cursor to the first line
//lcd.print("from master:");
//lcd.setCursor(0, 1); // Set the cursor to the second line
}
void loop()
{
Serial.println("I2C Communication"); //printing on serial monitor
Serial.print("MASTER DATA: ");
Serial.println(slaveReceived);
lcd.setCursor(0,0); //setting the cursor of LCD to the sarting
lcd.print("SLAVE LCD"); //printing on the LCD
lcd.setCursor(0,1);
lcd.print("MASTER DATA: ");
lcd.print(slaveReceived);
delay(500); //giving delay
lcd.clear(); //clearing the LCD
}
void receiveEvent(int howMany) //called function definition
{
slaveReceived = Wire.read(); //storing the data from master
}