Challenge

Project 1 - Interfacing a 16*2 LCD with Arduino using I2C protocol

Master

#include<Wire.h> //Library for I2C communication functions
#include<LiquidCrystal.h> //Library for LCD functions
LiquidCrystal lcd(2,7,8,9,10,11); //define lcd module pins(rs,en,D4,D5,D6,D7)

void setup()
{
lcd.begin(16,2); // initialize LCD display
lcd.setCursor(0,0); //set cursor at first line of display
lcd.print("Skill-Lync"); //prints in LCD
lcd.setCursor(0,1); //set cursor at second line of display
lcd.print("I2C Arduino to Arduino"); //prints in LCD
delay(2000);
lcd.clear(); //clears lcd display
Serial.begin(9600); //begins serial communication at 9600 baud rate
Wire.begin(); //begins I2C communication at pin A4,A5
}

void loop()
{
Wire.requestFrom(8,1); //requests 1 byte from slave arduino
byte MasterReceive = Wire.read(); //receives byte from slave and stores in MasterReceive
int potvalue = analogRead(A0); //reads analog value from potentiometer
byte MasterSend = map(potvalue,0,1023,0,127); //converts digital value 0-1023 to 0-127
Wire.beginTransmission(8); // start transmit to slave
Wire.write(MasterSend); //sends one byte converted pot value to slave
Wire.endTransmission(); //stops transmitting
lcd.setCursor(0,0); //sets cursor at first line of display
lcd.print(">> I'M Master <<"); //prints in lcd
lcd.setCursor(0,1);
lcd.print("SlaveVal:"); //prints Slave value in lcd
lcd.print(MasterReceive);
Serial.println("Master Received Frome Slave"); //prints in Serial monitor
Serial.println(MasterReceive);
delay(5000);
lcd.clear();
}

SLAVE

#include<Wire.h>
#include<LiquidCrystal.h>
LiquidCrystal lcd(2,7,8,9,10,11);
byte SlaveReceived = 0;
void setup()
{
lcd.begin(16,2);
lcd.setCursor(0,0);
lcd.print("Skill-Lync"); //prints in lcd
lcd.setCursor(0,1);
lcd.print("I2C to Arduino");
delay(5000);
lcd.clear();
Serial.begin(9600);
Wire.begin(8); //begins I2C communication with slave arduino
Wire.onReceive(receiveEvent); //function call when slave receives value from master
Wire.onRequest(requestEvent); //function call when master request value from slave
}

void loop()
{
lcd.setCursor(0,0);
lcd.print(">>I'M Slave <<");
lcd.setCursor(0,1);
lcd.print("MasterVal:");
lcd.print(SlaveReceived);
Serial.println("Slave Received From Master");
Serial.println(SlaveReceived);
delay(500);
lcd.clear();
}

void receiveEvent(int howMany) //function is called when slave receives value from master
{
SlaveReceived = Wire.read(); //used to read value received from master
}
void requestEvent() //function is called when Master wants value from slave
{
int potvalue = analogRead(A0); //reads analog value from pot (0-8V)
byte SlaveSend = map(potvalue,0,1023,0,127); //converts pot digital value
Wire.write(SlaveSend); //sends one byte converted pot value to master
}

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.