Friday, February 9, 2018

Switching Between Client Mode and Access Point Mode on Raspberry Pi

I'm working on a project to network my telescope. I have a Raspberry Pi Zero that is controlling a power focuser, and will eventually control scope motion by sending serial commands to the hand controller.

If I'm at home, I'd like to connect to my home network. If I'm away from home, I want it to act as an access point (AP) so that I can control the scope. This would also be really useful on a network controlled robot.

This was tested on a Pi Zero W, and should work on a Pi 3 as well. It assumes the Pi is currently configured to automatically connect to your home network. Pi's that use different USB wireless NICS will need a modification to the hostapd configuration file to reflect the driver name in use.

I'm using hostapd and the ISC DHCPD server, so first:

sudo apt-get install hostapd isc-dhcp-server

My /etc/hostapd/hostapd.conf file looks like this:

# WifI interface and driver to be used

# WiFi settings

# Use WPA authentication and a pre-shared key

# Network Name
# Network password

I appended the following network definition to /etc/dhcp/dhcpd.conf to define the range of addresses that it will hand out to clients when acting as an AP:

subnet netmask {
 option broadcast-address;
 option routers;
 default-lease-time 600;
 max-lease-time 7200;
 option domain-name "local";
 option domain-name-servers,;

The following script, when executed, will disconnect from any AP that the Pi is associated with and fire up the access point, setting a static IP for the Pi in the process:

sudo killall wpa_supplicant
sudo ifconfig wlan0 down
sudo ifconfig wlan0 netmask up
sudo service isc-dhcp-server start
sudo hostapd /etc/hostapd/hostapd.conf &

Then we just need to determine if we are connected or not when the Pi boots up.

First, I added an entry in /etc/rc.local to call this script, which checks to see if I'm connected to my home AP after a brief delay:

sleep 10
OUTPUT=$(iwconfig wlan0 | grep -c MyHomeSSID)

if [ "$OUTPUT" = "0" ]
        echo "Not associated to home AP, starting local AP"
        logger "Home AP not found, starting local AP"
        sudo /home/pi/startAP
        echo "Associated to home AP, no action taken"
        logger "Home AP found, not starting local AP"

1 comment:

  1. Thanks for all this info - I am trying to convert my table-top autotracker scope into a more automated system. I've managed to get the bluetooth function on the raspi-zero-W to work as a console. This allows me to pair with the laptop and run the AP script manually. This is great stuff thanks for sharing!