from machine import Pin
from time import sleep
# Define LCD pin connections for 4-bit mode
dataline = [Pin(5, Pin.OUT), Pin(4, Pin.OUT), Pin(3, Pin.OUT), Pin(2, Pin.OUT)]
e = Pin(10, Pin.OUT)
rs = Pin(11, Pin.OUT)
# Function to write a nibble to the LCD (4 bits at a time)
def write_nibble(val):
for i in range(4):
dataline[i].value((val >> i) & 0x01)
e.value(1) # Enable high
sleep(0.001)
e.value(0) # Enable low to latch data
sleep(0.001)
# Function to write a byte to the LCD in 4-bit mode (high nibble, then low nibble)
def write(val):
write_nibble(val >> 4) # Send the high nibble first
write_nibble(val & 0x0F) # Then send the low nibble
# Function to write data to the LCD
def datawrite(val):
rs.value(1) # Register select to data mode
write(val)
# Function to send commands to the LCD
def cmdwrite(val):
rs.value(0) # Register select to command mode
write(val)
sleep(0.01)
# Function to initialize the LCD in 4-bit mode
def startlcd():
cmdwrite(0x33) # Initialization command for 4-bit mode
cmdwrite(0x32) # Set to 4-bit mode
cmdwrite(0x28) # Function set: 4-bit, 2 lines, 5x7 dots
cmdwrite(0x0C) # Display ON, cursor OFF
cmdwrite(0x01) # Clear display
cmdwrite(0x80) # Move cursor to the beginning of the first line
sleep(0.01)
# Function to print a word on the LCD
def print_lcd(word):
for char in word:
datawrite(ord(char))
# Function to zero-fill a number for consistent formatting
def zfl(s, width):
return '{:0>{w}}'.format(s, w=width)
# Initialize and display initial text
startlcd()
cmdwrite(0x80) # Set cursor to the start of the first line
print_lcd("BMT 4033") # Display "BMT 4033" on the left side of the first line
cmdwrite(0xC0 + 4) # Move cursor to line 2, 5th position
print_lcd("EMBEDDED") # Display "EMBEDDED" centered on the second line
# Display the count up number from 0 to 80 on the first line next to "BMT 4033"
while True:
for i in range(0, 81, 2):
cmdwrite(0x80 + 10) # Set cursor to line 1, 11th position for the count
print_lcd("Cnt:" + zfl(str(i), 2)) # Display "Cnt: XX"
sleep(0.5) # Delay between increments