Project 1 - Interfacing a 16*2 LCD with Arduino using I2C protocol
The master Arduino will send a message to the slave Arduino.
#include <Wire.h>
const int slaveAddress = 8;
void setup() {
Wire.begin();
Serial.begin(9600);
delay(1000);
}
void loop() {
String message = "Hello, LCD!";
Wire.beginTransmission(slaveAddress);
Wire.write(message.c_str());
Wire.endTransmission();
Serial.println("Message sent: " + message);
delay(2000);
}
Slave Arduino Code (Receiver and LCD Display):
#include <Wire.h>
#include <LiquidCrystal_I2C.h> // Include the LiquidCrystal_I2C library for LCD
const int slaveAddress = 8; // The I2C address of this Slave Arduino
#define LCD_COLUMNS 16 // Number of columns on the LCD
#define LCD_ROWS 2 // Number of rows on the LCD
LiquidCrystal_I2C lcd(0x27, LCD_COLUMNS, LCD_ROWS); // Set the LCD I2C address to 0x27
String receivedMessage = ""; // String to store the received message
void setup() {
Wire.begin(slaveAddress); // Initialize the I2C bus as a Slave with the given address
Wire.onReceive(receiveEvent); // Register the receive event function
lcd.init(); // Initialize the LCD
lcd.backlight(); // Turn on the backlight
lcd.clear(); // Clear the display
Serial.begin(9600); // Initialize Serial communication for debugging
}
void loop() {
// The main loop remains empty since the work is done in the receiveEvent() function
}
void receiveEvent(int bytes) {
receivedMessage = ""; // Clear the previous message
while (Wire.available()) { // While data is available on the I2C bus
char c = Wire.read(); // Read each byte from the I2C bus
receivedMessage += c; // Append the character to the receivedMessage string
}
Serial.println("Message received: " + receivedMessage); // Debugging: Print the received message
lcd.clear(); // Clear the LCD screen
lcd.setCursor(0, 0); // Set cursor to the top left of the LCD
lcd.print(receivedMessage); // Display the received message on the LCD
}