Project 1 - Interfacing a 16*2 LCD with Arduino using I2C protocol
Answer
#include <Wire.h>
#define SLAVE_ADDRESS 9 // Address of the slave Arduino
void setup() {
Wire.begin(); // Initialize I2C communication as master
}
void loop() {
Wire.beginTransmission(SLAVE_ADDRESS); // Start transmission to slave
Wire.write("Hello, Slave!"); // Send message
Wire.endTransmission(); // End transmission
delay(1000); // Wait for a second before sending the next message
}
```
### Code for Slave Arduino (Receiver):
```cpp
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define SLAVE_ADDRESS 9 // Address of this Arduino as slave
#define LCD_COLS 16
#define LCD_ROWS 2
LiquidCrystal_I2C lcd(0x27, LCD_COLS, LCD_ROWS); // Address of the LCD I2C backpack
void setup() {
Wire.begin(SLAVE_ADDRESS); // Initialize I2C communication as slave
Wire.onReceive(receiveEvent); // Register event for receiving data
lcd.init(); // Initialize the LCD
lcd.backlight(); // Turn on the backlight
lcd.clear(); // Clear the LCD screen
}
void loop() {
// Nothing to do in the loop as data reception is handled by events
}
void receiveEvent(int bytes) {
while (Wire.available()) {
char c = Wire.read(); // Read the received byte
lcd.print(c); // Print the received character on the LCD
}
}