from machine import Pin, I2C
import time
# Initialize I2C (using GPIO 5 for SCL and GPIO 4 for SDA)
# These are standard I2C pins on many ESP32/ESP8266 boards
i2c = I2C(0, scl=Pin(5), sda=Pin(4)) # Set SCL to GPIO 5, SDA to GPIO 4
# LCD I2C Address (0x27 is most common for 20x4 LCD)
LCD_ADDR = 0x27
LCD_WIDTH = 20
LCD_HEIGHT = 4
# LCD Commands
LCD_CLEARDISPLAY = 0x01
LCD_RETURNHOME = 0x02
LCD_ENTRYMODESET = 0x04
LCD_DISPLAYCONTROL = 0x08
LCD_CURSORSHIFT = 0x10
LCD_FUNCTIONSET = 0x20
LCD_SETCGRAMADDR = 0x40
LCD_SETDDRAMADDR = 0x80
# Display control flags
LCD_DISPLAYON = 0x04
LCD_DISPLAYOFF = 0x00
LCD_CURSORON = 0x02
LCD_CURSOROFF = 0x00
LCD_BLINKON = 0x01
LCD_BLINKOFF = 0x00
# Entry mode flags
LCD_ENTRYRIGHT = 0x00
LCD_ENTRYLEFT = 0x02
LCD_ENTRYSHIFTINCREMENT = 0x01
LCD_ENTRYSHIFTDECREMENT = 0x00
# Function to send a command to the LCD
def lcd_send_command(command):
i2c.writeto(LCD_ADDR, bytes([0x00, command])) # Send the command byte (0x00 for command mode)
# Function to send data (text) to the LCD
def lcd_send_data(data):
i2c.writeto(LCD_ADDR, bytes([0x40, data])) # Send the data byte (0x40 for data mode)
# Initialize the LCD
def lcd_init():
time.sleep(0.1)
lcd_send_command(LCD_FUNCTIONSET | 0x08) # 4-bit mode, 2-line display, 5x8 matrix
lcd_send_command(LCD_DISPLAYCONTROL | LCD_DISPLAYON | LCD_CURSOROFF | LCD_BLINKOFF)
lcd_send_command(LCD_ENTRYMODESET | LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT)
lcd_send_command(LCD_CLEARDISPLAY) # Clear display
time.sleep(0.2)
# Set the cursor to a specific location on the LCD
def lcd_set_cursor(col, row):
if row == 0:
lcd_send_command(LCD_SETDDRAMADDR | col)
elif row == 1:
lcd_send_command(LCD_SETDDRAMADDR | (col + 0x40)) # Address for second row
elif row == 2:
lcd_send_command(LCD_SETDDRAMADDR | (col + 0x14)) # Address for third row
elif row == 3:
lcd_send_command(LCD_SETDDRAMADDR | (col + 0x54)) # Address for fourth row
# Write a string of text to the LCD
def lcd_write_string(string):
for char in string:
lcd_send_data(ord(char)) # Send the character to the LCD
# Initialize the LCD
lcd_init()
# Display "Hello, World!" on the first line
lcd_set_cursor(0, 0) # Set cursor to the first row, first column
lcd_write_string("Hello, World!")
# Display your name on the second line
lcd_set_cursor(0, 1) # Set cursor to the second row, first column
lcd_write_string("Your Name")
# Wait for 5 seconds to keep the text on the screen
time.sleep(5)
# Clear the display after the delay
lcd_send_command(LCD_CLEARDISPLAY)