Restart WiFi on raspberry pi zero when it loses its connection

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Restart WiFi on raspberry pi zero when it loses its connection

    The script below restarts wifi on your raspberry pi when wifi crashes or your pi cant connect to your network.

    Login via ssh to your raspberry pi,

    default username is: pi
    default password is: raspberry

    Go to folder /usr/local/bin
    Code:
    cd /usr/local/bin
    create a file restartwifi.sh
    Code:
    sudo nano restartwifi.sh
    Copy and paste the contents below into the file,
    change 192.168.0.1 to ip address of your router.

    Code:
    #!/bin/bash
    
    # The IP for the server you wish to ping (8.8.8.8 is a public Google DNS server)
    SERVER=192.168.0.1
    
    # Only send two pings, sending output to /dev/null
    ping -c2 ${SERVER} > /dev/null
    
    # If the return code from ping ($?) is not 0 (meaning there was an error)
    if [ $? != 0 ]
    then
        # Restart the wireless interface
        #ifdown --force wlan0
        #ifup wlan0
        ifconfig wlan0 down
        sleep 5
        ifconfig wlan0 up
    fi
    press ctrl+x to exit nano, save the file with y.

    now we have to create a cronjob which will check wifi every 15 minutes, and if there is no connection to router to restart it.
    Code:
    sudo nano crontab -e
    select nano as editor.

    add at the end of file this line:
    Code:
    */15 * * * * /usr/bin/sudo -H /usr/local/bin/restartwifi.sh >> /dev/null 2>&1
    press ctrl+x to exit nano, save the file with y.

  • #2
    Nice Gums. I recently started getting into this.

    Comment

    Working...
    X