Automatically reconnect to WiFi on Raspberry Pi
The Raspberry Pi sometimes disconnects from the WiFi.
The main reason for this could be low power. Make sure there'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, there are two ways around this problem.
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 problem. It runs every 5 minutes and reconnects the Raspberry Pi to the WiFi network if it is disconnected.
# WiFi connectivity test (and reconnect if needed)
# Source: https://feriman.com/automatically-reconnect-to-wifi-on-raspberry-pi/
#
# Check the connectivity
if ! ping -c2 8.8.8.8 > /dev/null; then
# Shut down the wlan0 adapter if the network is not reachable
ifconfig wlan0 down
# Sleep 2 seconds to be sure
sleep 2
# Start the wlan0 adapter again
# It will reconnect to the WiFi automatically
ifconfig wlan0 up
# 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
That's all. If you have any other solution, leave a comment below.
If you're looking for Raspberry Pi monitoring, click here
Comments