Project 1 - Interfacing a 16*2 LCD with Arduino using I2C protocol
for slave
#include <Wire.h>
#include <LiquidCrystal.h>
#define SLAVE_ADDR 8 // I2C address of this slave
// Initialize the LCD with the pins connected to the Arduino
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
void setup() {
Wire.begin(SLAVE_ADDR); // Join I2C bus with address
Wire.onReceive(receiveEvent); // Register event handler for receiving data
lcd.begin(16, 2); // Initialize the 16x2 LCD
}
void loop() {
// Nothing to do in the main loop, waiting for I2C communication
}
void receiveEvent(int howMany) {
String receivedMessage = "";
while (Wire.available()) {
char c = Wire.read(); // Read a character from the I2C bus
receivedMessage += c; // Append the character to the received message
}
lcd.clear(); // Clear the LCD screen
lcd.setCursor(0, 0); // Set cursor to the first row
lcd.print(receivedMessage); // Display received message on the LCD
}
for master
#include <Wire.h>
#define SLAVE_ADDR 8 // I2C address of the slave
void setup() {
Wire.begin(); // Join I2C bus as master
Serial.begin(9600);
}
void loop() {
Wire.beginTransmission(SLAVE_ADDR);
Wire.write("Hello, World!"); // Message to send
Wire.endTransmission();
delay(2000); // Wait for 2 seconds before sending the next message
}