Skip to content

Instantly share code, notes, and snippets.

@rfong
Last active April 4, 2024 02:09
Show Gist options
  • Save rfong/2c36b87ff22077f8dd9afd513c519a80 to your computer and use it in GitHub Desktop.
Save rfong/2c36b87ff22077f8dd9afd513c519a80 to your computer and use it in GitHub Desktop.
Display my IP address on an I2C OLED screen #raspberrypi #gpio

Adafruit setup tutorial can be found here

Dependencies

For Raspberry Pi

sudo apt-get update
sudo apt-get install build-essential python-dev python-pip
sudo pip install RPi.GPIO
sudo apt-get install python-imaging python-smbus

Enable I2C

Get the Python lib

sudo apt-get install git
git clone https://github.com/adafruit/Adafruit_Python_SSD1306.git
cd Adafruit_Python_SSD1306
sudo python setup.py install

sudo is required to use GPIO.

Wiring

Raspberry Pi pinout diagram

If you have a 4-pin I2C breakout: connect SDA, SCL, GND to their corresponding Raspberry Pi pins; VCC to 3.3V. Otherwise, follow the wiring examples here.

""" Display my IP address on an I2C OLED screen connected over GPIO """
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
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 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
try:
while 1: # Try forever because this is an example
ip_addr = get_ip()
if ip_addr:
draw_text("IP: " + 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()
#!/bin/sh -e
# Put me at /etc/rc.local to run on boot.
sudo python /path/to/I2C_SSD1306_ipaddr.py &
exit 0;
@Killaship
Copy link

This worked perfectly! Thanks for writing this, it helps a lot.

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