Project 1 - Interfacing a 16*2 LCD with Arduino using I2C protocol
Interfacing a 16*2 LCD with Arduino using I2C protocol
Master code
#include<Wire.h>//i2c communication hedder file
#include <LiquidCrystal.h>//lcd disply headder file
LiquidCrystal lcd(12,11,5,4,3,2);
void setup()
{
lcd.begin(16,2);
lcd.setCursor(0,0);
lcd.print("Ultrasonicsensor");
delay(5000);
lcd.clear();
Wire.begin(); //enable the I2C communication
}
void loop()
{
Wire.requestFrom(1,2); //address of slave and bytes quatity
byte CMReceive = Wire.read();//receive data from slave
lcd.begin(16,2);
lcd.setCursor(0,0);
lcd.print("Distance in CM");
lcd.setCursor(0,1);
lcd.print(CMReceive);
delay(2000);
lcd.clear();
byte INCHReceive = Wire.read();//receive from slave
lcd.begin(16,2);
lcd.setCursor(0,0);
lcd.print("Distance in INCH");
lcd.setCursor(0,1);
lcd.print(INCHReceive);
delay(3000);
lcd.clear();
}
Slave code
#include<Wire.h>
int CM = 0;
int inch = 0;
int duration = 0; // variable decleration
void setup()
{
pinMode(12, OUTPUT); // pin mode decleration
pinMode(11, INPUT);
Wire.begin(1); //i2c communication begin
Wire.onRequest(requestEvent); // recieve from master
}
void loop()
{
}
void requestEvent() // isr fun
{
digitalWrite(12, LOW);
delayMicroseconds(2);
digitalWrite(12, HIGH);
delayMicroseconds(2);
digitalWrite(12, LOW);
duration = pulseIn(11, HIGH); //ultrosonic wave time travel
CM = 0.01723 * duration;// formula to convert the cm
Wire.write(CM);//write the value in wire
inch = (CM / 2.54); // inch conversion
Wire.write(inch);//write the value in wire
}
