Project 1 - Interfacing a 16*2 LCD with Arduino using I2C protocol
Master Aduino Code:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 16, 2); // set the LCD address to 0x3F for a 16 chars and 2 line display
void setup() {
Wire.begin(); // join i2c bus (address optional for master)
lcd.init(); // initialize the LCD
lcd.backlight(); // turn on the backlight
lcd.setCursor(0, 0); // set the cursor to the first column and first row
lcd.print("Hello, world!"); // print a message to the LCD
}
void loop() {
// send a message to the slave every 2 seconds
Wire.beginTransmission(8); // transmit to slave device at address 8
Wire.write("Hello from master!"); // send a message to the slave
Wire.endTransmission(); // stop transmitting
delay(2000); // wait for 2 seconds
}
Slave Arduino Code:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 16, 2); // set the LCD address to 0x3F for a 16 chars and 2 line display
void setup() {
Wire.begin(8); // join i2c bus with address #8
Wire.onReceive(receiveEvent); // register receive event handler
lcd.init(); // initialize the LCD
lcd.backlight(); // turn on the backlight
}
void loop() {
// do nothing in the loop function
}
void receiveEvent(int bytes) {
while (Wire.available()) {
char c = Wire.read(); // read the message sent by the master
lcd.clear(); // clear the LCD
lcd.setCursor(0, 0); // set the cursor to the first column and first row
lcd.print("Received:"); // print a message to the LCD
lcd.setCursor(0, 1); // set the cursor to the first column and second row
lcd.print(c); // print the received message to the LCD
}
}