import machine
import utime
from machine import I2C
# I2C LCD Address
LCD_I2C_ADDR = 0x27 # You may need to adjust this address based on your LCD module
# Define some constants for LCD control
LCD_CLEAR = 0x01
LCD_RETURN_HOME = 0x02
LCD_ENTRY_MODE_SET = 0x04
LCD_DISPLAY_CONTROL = 0x08
LCD_FUNCTION_SET = 0x20
LCD_SET_CGRAM_ADDR = 0x40
LCD_SET_DDRAM_ADDR = 0x80
# LCD Backlight Control
LCD_BACKLIGHT = 0x08 # On
# LCD_BACKLIGHT = 0x00 # Off
# Define the LCD size and line addresses (for a 16x2 display)
LCD_WIDTH = 16
LCD_LINE_1 = 0x80 # Address for the first line
LCD_LINE_2 = 0xC0 # Address for the second line
# Initialize I2C communication
i2c = I2C(0, scl=machine.Pin(1), sda=machine.Pin(0), freq=400000) # Use GPIO 0 and 1 for I2C
def lcd_send_command(cmd):
i2c.writeto(LCD_I2C_ADDR, bytearray([cmd]))
def lcd_send_data(data):
i2c.writeto(LCD_I2C_ADDR, bytearray([0x40, data]))
def lcd_initialize():
# Initialize the LCD (4-bit mode)
utime.sleep_ms(50)
lcd_send_command(0x30)
utime.sleep_ms(5)
lcd_send_command(0x30)
utime.sleep_ms(1)
lcd_send_command(0x30)
utime.sleep_ms(1)
lcd_send_command(0x20)
utime.sleep_ms(1)
# Configure LCD display
lcd_send_command(LCD_FUNCTION_SET | 0x08) # 2 lines, 5x8 character font
lcd_send_command(LCD_DISPLAY_CONTROL | 0x04) # Display on, cursor off, blink off
lcd_send_command(LCD_CLEAR) # Clear the LCD
utime.sleep_ms(2)
lcd_send_command(LCD_ENTRY_MODE_SET | 0x06) # Entry mode: Increment cursor, no shift
def lcd_clear():
lcd_send_command(LCD_CLEAR)
utime.sleep_ms(2)
def lcd_set_cursor(col, row):
if row == 0:
lcd_send_command(LCD_SET_DDRAM_ADDR | (col % LCD_WIDTH))
elif row == 1:
lcd_send_command(LCD_SET_DDRAM_ADDR | (0x40 + col % LCD_WIDTH))
elif row == 2:
lcd_send_command(LCD_SET_DDRAM_ADDR | (0x14 + col % LCD_WIDTH))
elif row == 3:
lcd_send_command(LCD_SET_DDRAM_ADDR | (0x54 + col % LCD_WIDTH))
def lcd_display_message(message, row):
lcd_set_cursor(0, row)
for char in message:
lcd_send_data(ord(char))
# Initialize the LCD
lcd_initialize()
# Clear the LCD
lcd_clear()
# Display a message
lcd_display_message("Hello, RP2040!", 0)
lcd_display_message("I2C LCD Interface", 1)