Skip to content

Instantly share code, notes, and snippets.

@mijorus
Last active September 5, 2025 10:56
Show Gist options
  • Save mijorus/e9cc50fdf7e54e69e2819f971fba183b to your computer and use it in GitHub Desktop.
Save mijorus/e9cc50fdf7e54e69e2819f971fba183b to your computer and use it in GitHub Desktop.
Automatically create a Wifi Hotspot on a Raspberry PI if the board is not connected to the internet of PI Zero

With this script, the power LED will start flashing green for 1 minute, signaling that the hotspot is turned on.

You can than connect to it with your PC and login ssh [email protected]

Create an autohotspot.sh under /home/pi

#!/usr/bin/bash

ap_ssid="RaspberryPi-AP"
ap_password="raspberry"

check_wlan0_connected() {
    local wlan_state=$( nmcli connection show --active | grep -E "wlan0\s ")
    if [ -n "$wlan_state" ]; then
        return 0  # true - connected
    fi

    return 1  # false - not connected
}

is_pi_zero() {
    if [ -f /proc/device-tree/model ]; then
        local model=$(cat /proc/device-tree/model | tr -d '\0')
        if [[ "$model" == *"Pi Zero"* ]]; then
            return 0  # true - is Pi Zero
        fi
    fi

    return 1  # false - not Pi Zero
}

if [ "$(whoami)" != "root" ]; then
    echo "This script must be run as root"
    exit 1
fi

echo "Checking WiFi connection..."

counter=0
# Loop for a maximum of 15 seconds
while [ $counter -lt 15 ]; do
    echo "Check #${counter}"

    # Check if connected to WiFi network
    if check_wlan0_connected; then
        echo "Connected to internet via WiFi"
        exit 0
    fi

    sleep 1
    counter=$((counter + 1))  # Increment the counter by 1 each second
done

echo "No connection, switching to AP mode"
nmcli device wifi hotspot ssid ${ap_ssid} password ${ap_password} ifname wlan0

if is_pi_zero; then
    echo heartbeat | sudo tee /sys/class/leds/ACT/trigger
fi

exit 0

Make it executable

sudo chmod +x autohotspot.sh

Create a systemd service

sudo nano  /etc/systemd/system/autohotspot.service   
Description=AutoHotSpot Script
After=network.target
Wants=network.target

[Service]
Type=oneshot
ExecStart=/home/pi/autohotspot.sh
User=root
Group=root
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target

Start the service

sudo systemctl enable autohotspot.service
sudo systemctl start autohotspot.service
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment