Automatically reconnect to WiFi on Raspberry Pi

Automatically reconnect to WiFi on Raspberry Pi

The Raspberry Pi sometimes disconnects from the WiFi.

The main reason could be the weak power supply. Be sure that it's enough by running this command:

/bin/dmesg | grep 'Under-voltage detected'

If there's any result, consider buying an official power supply from Aliexpress or eBay.

If you have a good power supply, I have two different ways to work around this issue.

Method #1

Turn off the WiFi power management by running this command:

sudo /sbin/iwconfig wlan0 power off

Insert this below command in crontab by running crontab -e to disable it automatically on startup:

@reboot /bin/sleep 10 && sudo /sbin/iwconfig wlan0 power off

Method #2

I wrote a simple script to work around this issue. It will run every 5 minutes and reconnect the Raspberry Pi to the WiFi network if it is disconnected.

# WiFi connectivity test (and reconnect if needed)
# Source: https://feriman.com
#
# Check the connectivity 
if ! ping -c2 8.8.8.8 > /dev/null; then
# Shut down the wlan0 adapter if the network is not reachable
        ifdown --force wlan0
 # Sleep 2 seconds to be sure
        sleep 2
# Start the wlan0 adapter again
# It will reconnect to the WiFi automatically
        ifup wlan0
# Sleep 10 seconds to be sure
        sleep 10
 # Put here all services with network dependencies
        systemctl restart smbd ssh rpimonitor rtorrent apache2
fi

Paste this script into a file and give execute permission:

nano /home/pi/reconnect-wifi.sh

chmod +x /home/pi/reconnect-wifi.sh

And schedule it in the root crontab:

sudo su

crontab -e

*/5 * * * * /home/pi/reconnect-wifi.sh

If you have any other solution, leave a comment below.

 

If you're looking for Raspberry Pi monitoring, click here

Comments