Skip to content

Instantly share code, notes, and snippets.

@raoulduke
Created March 5, 2026 06:47
Show Gist options
  • Select an option

  • Save raoulduke/c2a727c4dcf0dcc294a1e82e231e4619 to your computer and use it in GitHub Desktop.

Select an option

Save raoulduke/c2a727c4dcf0dcc294a1e82e231e4619 to your computer and use it in GitHub Desktop.
Raspberry Pi - Display IP address on LCD module on boot
import time
import netifaces
from RPLCD.i2c import CharLCD
import fcntl
# --- Configuration ---
WIFI_IFACE = "wlan0"
LCD_I2C_ADDR = 0x27
LOCK_FILE = "/tmp/lcd.lock"
# --- LCD Setup ---
lcd = CharLCD(i2c_expander="PCF8574", address=LCD_I2C_ADDR, cols=16, rows=2, charmap="A00", auto_linebreaks=False)
lcd.clear()
# --- Helper Functions ---
def get_ip_address(interface=WIFI_IFACE):
"""Return the IPv4 address of the interface, or None if not up."""
try:
addrs = netifaces.ifaddresses(interface)
if netifaces.AF_INET in addrs:
return addrs[netifaces.AF_INET][0]['addr']
except (ValueError, KeyError):
return None
return None
def safe_lcd_write(lines):
"""Write to LCD safely using a file lock."""
with open(LOCK_FILE, "w") as lockfile:
fcntl.flock(lockfile, fcntl.LOCK_EX)
lcd.clear()
for i, line in enumerate(lines):
if i > 1: # LCD has only 2 lines
break
lcd.cursor_pos = (i, 0)
lcd.write_string(line)
fcntl.flock(lockfile, fcntl.LOCK_UN)
def display_connecting():
safe_lcd_write(["Connecting to", WIFI_IFACE])
def display_ip(ip):
safe_lcd_write(["Connected", ip])
# --- LCD Update Loop ---
def lcd_update_loop():
display_connecting()
while True:
ip = get_ip_address()
if ip:
display_ip(ip)
break
time.sleep(1)
# --- Run ---
lcd_update_loop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment