Blink out IP address for Raspberry Pi using Python

So in the final chapter of the long saga that has been connecting my Raspberry Pi to my Campus’s WiFi network, I needed a way to obtain the IP address of the Pi without using a display or a serial cable.

I’m actually pretty proud of this and I think it’s an elegant solution to a fairly annoying problem. Here’s a video of the system in action:

The program starts with three blinks. After that, the pattern goes as follows:

Blink Blink Blink Pause = 3
Blink Blink Pause = 2

So

Blink Blink Blink Pause Blink Blink Blink Blink Pause Blink = 341

Etc. Four short blinks indicate a 0 and six short blinks indicate a “.”

Once the address is fully read out, three long blinks will occur.

Here’s the code:

import RPi.GPIO as GPIO ## Import GPIO library

import time
GPIO.setmode(GPIO.BCM) ## Use board pin numbering

led = 20
button = 21

GPIO.setup(led, GPIO.OUT) ## Setup GPIO Pin 7 to OUT
GPIO.setup(button, GPIO.IN)

from subprocess import *

while 1:
	if (GPIO.input(button)):
	
		ip = Popen("ip addr show wlan0 | grep inet | awk '{print $2}' | cut -d/ -f1", shell=True, stdout=PIPE).communicate()[0]
			
		for x in range(3): #three rapid blinks to indicate procedure is starting
			
			GPIO.output(led,True)
			time.sleep(.2)
			GPIO.output(led,False)
			time.sleep(.2)
		
		time.sleep(3) # followed by a delay
		
		for x in list(ip):
		
			time.sleep(4) #a long delay between characters
			
			if x.isdigit():
				if (int(x) == 0):
					for x in range(4): #four rapid blinks indicate a 0
						
						GPIO.output(led,True)
						time.sleep(.2)
						GPIO.output(led,False)
						time.sleep(.2)
					
									
				elif (int(x) != 0):
					for y in range(int(x)):
						
						GPIO.output(led,True)
						time.sleep(.5)
						GPIO.output(led,False)
						time.sleep(.5)

			elif (x == '.'):
				for x in range(6): #six rapid blinks indicate a .
					
					GPIO.output(led,True)
					time.sleep(.1)
					GPIO.output(led,False)
					time.sleep(.1)
		
				time.sleep(5)
			
			elif (x == '\n'):
				for x in range(3): #six rapid blinks indicate a '.'
					
					GPIO.output(led,True)
					time.sleep(2)
					GPIO.output(led,False)
					time.sleep(2)
		

You can make it run every time the Pi boots with:

crontab -e

Add the following line:

@reboot screen -d -m sudo python /path/to/script/Blink_IP.py

And your good to go! You can now press the button any time the pi boots to get the IP address without connecting anything!

4 Comments

  1. any way to make this use the onboard status LED? i know it’s possible to toggle that on and off.. just not sure how difficult that would be to do.

    1. Hey dan, thanks for commenting – I know it’s possible, but didn’t know how to do it at the time. Let me know if you try it!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.