Challenge

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

Code for Master:

//master
#include <Wire.h>
#include <LiquidCrystal.h>


const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
int distance;

void setup()
{
lcd.begin(16, 2);
lcd.print("Master");
delay(1000);
lcd.clear();
Wire.begin();
Serial.begin(9600);
}

void loop() {
Wire.requestFrom(1,1);
byte MasterReceive = Wire.read();
lcd.setCursor(0, 0);
lcd.print("data from slave");
lcd.setCursor(0, 1);
delay (500);

lcd.print("distance: ");
lcd.print(MasterReceive);

}

Code for Slave:

//Slave
#include <LiquidCrystal.h>
#include<Wire.h>

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
const int trigPin = 7;
const int echoPin = 8;
long duration;
int distance;
int slaveReceive;

void setup() {
lcd.begin(16, 2);
lcd.setCursor(0, 0);
lcd.print("Slave");
delay(1000);
lcd.clear();
Wire.begin();
Wire.begin(1);
Wire.onReceive(receiveRequest);
Wire.onRequest(requestEvent);
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600);

}

void loop(void)
{
}
void requestEvent()
{

digitalWrite(trigPin, LOW);
delay(2000);
lcd.clear();
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delay(100);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2;
// Prints the distance on the Serial Monitor
Wire.write(distance);
lcd.setCursor(0,0);

lcd.print("Distance: ");
lcd.print(distance);
Serial.println("Distance: ");
Serial.print(distance);

}
void receiveRequest(int slaveReceive)
{
slaveReceive = Wire.read();
lcd.setCursor(0,0);
lcd.print("Data from master");
lcd.setCursor(1,1);
lcd.print(slaveReceive);


}

Output:

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.