My Raspberry Pi 3 Wi-Fi isn’t very reliable even after disabling power management my RPI still manages to lose connection to  my Wi-Fi router and i don’t have any keyboard or screen connected to it and its not advisable to do hard reset i.e unplug the power as it may corrupt your SD card. I’m going to cover writing a short script that Auto Reconnect WiFi on Raspberry Pi to a Wi-Fi network. The script will run as cron job at around 5 minutes interval to check if the Pi has network connectivity and if it is offline, restart the wireless interface to bring it back online.

There are a few ways to determine if the Raspberry Pi has Wi-Fi network connectivity. I’ll be using ping to determine Wi-Fi connection status.

Auto Reconnecting Wi-Fi Script

First we need to determine if the Raspberry Pi is connected to the Wi-Fi network. To do this, we can ping a our Wi-Fi router if you want to test internet connectivity you can use google DNS IP address 8.8.8.8 instead but we only want to check connection to our Wi-Fi router. If Raspberry Pi receives a ping response from the Wi-Fi router then we have network connectivity. If the we don’t get any response then we’ll turn wlan0 off and back on.

Copy and paste following script and save it (check_wifi.sh) i have all my cron schedules scripts saved under /var/www/cron you can save it to anywhere you like.

Make your script executable by running following command

Test Auto Reconnecting Wi-Fi Script

First run following command to test there are not errors in your script.

After successful execution of Auto Reconnecting Wi-Fi script you should get output as below.

Auto Reconnecting WiFi on a Raspberry Pi

Auto Reconnecting Wi-Fi on a Raspberry Pi

Lets add Auto Reconnecting Wi-Fi script to cron schedule so this script runs every five minutes. run crontab -e command and add following line to your crontab, make sure you add >/dev/null 2>&1 otherwise you will end up burning your SD card with unnecessary logs.

Lets do more testing taking down wlan0 and let script to restart Wi-Fi.

Note: running following command will immediately disconnect your shell session. and you have to wait for cron job to start your Wi-Fi it shouldn’t take more then 5 minutes.

After waiting for cron job to run auto reconnecting Wi-Fi script you can try to ssh to your raspberry pi. Assuming everything worked as it should your raspberry pi should reconnect to Wi-Fi. You can adjust time of script to what ever you value you like.