Project 1 - Interfacing a 16*2 LCD with Arduino using I2C protocol
Master Code :
#include <Wire.h>
#define SLAVE_ADDRESS 0x04 // I2C address of the slave
void setup() {
Wire.begin(); // Initialize I2C communication as master
Serial.begin(9600); // Initialize serial communication for debugging
delay(1000); // Wait for the setup to complete
}
void loop() {
// Send a message to the slave
Wire.beginTransmission(SLAVE_ADDRESS);
Wire.write("Hello, Dear!");
Wire.endTransmission();
delay(2000); // Wait for 2 seconds before sending the next message
}
Slave code :
// C++ code
#include <Wire.h>
#include <LiquidCrystal.h>
#define SLAVE_ADDRESS 0x04 // I2C address of the slave
// Initialize the LCD library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup() {
Wire.begin(SLAVE_ADDRESS); // Initialize I2C communication as slave with address 0x04
Wire.onReceive(receiveEvent);
lcd.begin(16, 2);
lcd.print("Waiting for msg");
}
void loop() {
delay(100);
}
void receiveEvent(int howMany)
{
char message[32];
int i = 0;
while (Wire.available()) {
char c = Wire.read();
message[i++] = c;
}
message[i] = '\0'; // Null terminate the string
// Clear the LCD and print the received message
lcd.clear();
lcd.print(message);
}