Project 1 - Interfacing a 16*2 LCD with Arduino using I2C protocol
// Master Arduino
#include
#include
LiquidCrystal lcd(12, 11, 5, 4, 3, 2); //Define LCD Module Pins (RS,EN,D4,D5,D6,D7)
void setup()
{
lcd.begin(16,2); //Initilize LCD display
lcd.setCursor(0,0);
lcd.print("I2C MASTER ARDUINO");
delay(5000); //Delay for 5 seconds
lcd.clear(); //Clears LCD display
Serial.begin(9600);
Wire.begin();
}
void loop()
{
Wire.requestFrom(8,1); // request 1 byte from slave arduino (8)
byte MasterReceive = Wire.read(); // receive a byte from the slave arduino and store in MasterReceive
int potvalue = analogRead(A1); // 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(8); // start transmit to slave arduino (8)
Wire.write(MasterSend); // sends one byte converted POT value to slave
Wire.endTransmission(); // stop transmitting
lcd.setCursor(0,0);
lcd.print(" Master ");
lcd.setCursor(0,1);
lcd.print("SlaveVal: ");
lcd.print(MasterReceive);
Serial.println("Master Received From Slave");
delay(500);
lcd.clear();
}
// Slave Arduino
#include
#include
LiquidCrystal lcd(12, 11, 5, 4, 3, 2); //Define LCD Module Pins (RS,EN,D4,D5,D6,D7)
byte SlaveReceived = 0;
void setup()
{
lcd.begin(16,2);
lcd.setCursor(0,0);
lcd.print("I2C SLAVE ARDUINO");
delay(5000);
lcd.clear();
Serial.begin(9600);
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);
}
void loop(void)
{
lcd.setCursor(0,0); //Sets Currsor at line one of LCD
lcd.print(" Slave "); //Prints >> Slave << at>
lcd.setCursor(0,1); //Sets Cursor at line two of LCD
lcd.print("Master Val: "); //Prints MasterVal: in 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();
}
void receiveEvent (int howMany) //This Function is called when Slave receives value from master
{
SlaveReceived = Wire.read(); //Used to read value received from master and store in variable SlaveReceived
}
void requestEvent()
{
int potvalue=analogRead(A1);
byte slavesend=map(potvalue,0,1023,0,127);
Wire.write(slavesend);
}