6

I have a Raspberry Pi with a WiFi dongle, so the standard internet LEDs don't work. I tried to write a script that toggles an LED whether the Pi have internet or not.

This is what I have for now:

#!/usr/bin/python
import urllib2 
import time, os

os.system("gpio mode 6 out && gpio mode 5 out")

loop_value = 1

while (loop_value == 1):
    try:
        urllib2.urlopen("http://www.google.com")
    except urllib2.URLError, e:
        time.sleep( 1 )
        print "Not Connected"
        os.system("gpio write 6 0 && gpio write 5 1")
    else:
       print "Connected"
       os.system("gpio write 6 1 && gpio write 5 0")
       loop_value = 1

The problem is that is isn't working. can someone tell me how I can detect it my pi has internet or not and then print toggle the LEDs?

Infinite Recursion
  • 6,511
  • 28
  • 39
  • 51
David Gölzhäuser
  • 3,525
  • 8
  • 50
  • 98
  • You don't need to use `loop_value` *at all*. Just use `while True:`, and use `break` when you want to stop the loop. Not your core problem, but wiltl make your code much more readable. – Martijn Pieters Jun 25 '13 at 17:57
  • Oh, and you really want to fix your indentation in your post, it is not legal Python as it stands. – Martijn Pieters Jun 25 '13 at 17:57

1 Answers1

8

Fixed indentation. break on successful url fetch.

#!/usr/bin/python
import os
import time
import urllib2 

os.system("gpio mode 6 out && gpio mode 5 out")

while True:
    try:
        urllib2.urlopen("http://www.google.com").close()
    except urllib2.URLError:
        print "Not Connected"
        os.system("gpio write 6 0 && gpio write 5 1")
        time.sleep(1)
    else:
        print "Connected"
        os.system("gpio write 6 1 && gpio write 5 0")
        break
falsetru
  • 357,413
  • 63
  • 732
  • 636