Skip to content

Instantly share code, notes, and snippets.

@SyedAhkam
Created December 19, 2022 18:14
Show Gist options
  • Save SyedAhkam/59742b7d6d5c899f26af6ab3dff9406e to your computer and use it in GitHub Desktop.
Save SyedAhkam/59742b7d6d5c899f26af6ab3dff9406e to your computer and use it in GitHub Desktop.
Display all network interfaces' IP address on an I2C OLED screen connected over GPIO
""" Display all network interfaces' IP address on an I2C OLED screen connected over GPIO (mainly for a raspberry pi) """
import socket
import time
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import Adafruit_GPIO.SPI as SPI
import Adafruit_SSD1306
import RPi.GPIO as GPIO
import netifaces
GPIO.setmode(GPIO.BCM)
RST = 24
disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, i2c_address=0x3C)
def get_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip_addr = s.getsockname()[0]
s.close()
return ip_addr
def all_ips():
ip = dict()
for interface in netifaces.interfaces():
try:
out = netifaces.ifaddresses(interface)[netifaces.AF_INET]
except KeyError:
ip[interface] = "X_X"
else:
ip[interface] = out[0]["addr"]
return ip
def main():
# Setup display
disp.begin()
disp.clear()
disp.display()
# Create blank image for drawing.
# Make sure to create image with mode '1' for 1-bit color.
width = disp.width
height = disp.height
image = Image.new('1', (width, height))
# Get drawing object to draw on image.
draw = ImageDraw.Draw(image)
font = ImageFont.load_default()
# Draw a black filled box to clear the image.
draw.rectangle((0,0,width,height), outline=0, fill=0)
def draw_text(text, line=0):
draw.text((5, 5 + line * 10), text, font=font, fill=1)
# Check & redraw IP address
old_ip = ""
try:
while 1: # Try forever because this is an example
ip_addr = ""
for key, value in all_ips().items():
ip_addr += f"{key}:{value}\n"
if ip_addr != old_ip:
draw.rectangle((0,0,width,height), outline=0, fill=0)
old_ip = ip_addr
if ip_addr:
draw_text(ip_addr)
else:
draw_text("Searching for Wi-Fi...")
disp.image(image)
disp.display()
time.sleep(.01)
except KeyboardInterrupt:
GPIO.cleanup()
if __name__ == '__main__':
main()
@RoguedBear
Copy link

original credit/fork of: rfong/I2C_SSD1306_ipaddr.py

script modified to display IP addresses detected on all interfaces

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment