Project 1 - Interfacing a 16*2 LCD with Arduino using I2C protocol
Master Programming
#include<Wire.h> //Library for I2C Communication functions
#include<LiquidCrystal.h> //Library for LCD display function
LiquidCrystal lcd(4, 6, 11, 12, 13, 14); //Define LCD Module Pins (RS,EN,D4,D5,D6,D7)
void setup()
{
lcd.begin(16,2); //Initilize LCD display
lcd.setCursor(0,0); //Sets Cursor at first line of Display
Serial.begin(9600); //Begins Serial Communication at 9600 baud rate
Wire.begin(); //Begins I2C communication at pin (A4,A5)
}
void loop()
{
Wire.requestFrom(1,1); // request 1 byte from slave arduino (8)
byte MasterReceive = Wire.read(); // receive a byte from the slave arduino
int potvalue = analogRead(A0); // Reads analog value from POT (0-5V)
byte MasterSend = map(potvalue,0,1023,0,127); //Convert digital value (0 to 1023) to (0 to 127)
Wire.beginTransmission(1); // start transmit to slave arduino (8)
Wire.write(MasterSend); // sends one byte converted POT value to slave
Wire.endTransmission(); // stop transmitting
//Prints MasterReceive in LCD received from Slave
Serial.println("Master Received From Slave"); //Prints in Serial Monitor
Serial.println(MasterReceive);
delay(500);
lcd.clear();
}
Slave Program
#include<Wire.h> //Library for I2C Communication functions
#include<LiquidCrystal.h> //Library for LCD display function
byte SlaveReceived = 0;
void setup()
{
lcd.begin(16,2); //Initilize LCD display
lcd.setCursor(0,0); //Sets Cursor at first line of Display
Serial.begin(9600); //Begins Serial Communication at 9600 baud rate
Wire.begin(8); //Begins I2C communication with Slave Address as 8 at pin (A4,A5)
Wire.onReceive(receiveEvent); //Function call when Slave receives value from master
Wire.onRequest(requestEvent); //Function call when Master request value from Slave
}
void loop(void)
{
lcd.setCursor(0,0); //Sets Currsor at line one of LCD
lcd.print(SlaveReceived); //Prints SlaveReceived value in LCD received from Master
Serial.println("Slave Received From Master:"); //Prints in Serial Monitor
Serial.println(SlaveReceived);
delay(500);
lcd.clear();
}