Raspberry Pi WiFi Configuration Switch

I’ve been working on my DIY racing telemetry system recently, and I find myself switching my Pi between a WiFi access point and WiFi end point quite a bit while testing. I normally have to hook up the Pi to an ethernet port so that I can ssh into it and switch the configuration, but I’ve just found a much more elegant solution!

The solution makes use of a GPIO pin and a physical switch to detect which configuration the Pi should use. Here’s the bash script I wrote. It sets the GPIO pin to an input with its internal pullup resistor enabled. I enabled the pullup resistor because I didn’t want the pin to float when my custom Pi hat was disconnected. The script then enters into an infinite while loop that polls the pin state every 5s to update the WiFi configuration. You can easily modify this script to do something completely different by changing the contents of the inner if-statement.

#!/bin/bash
# GPIO pin used for toggling WiFi between 
# end-point and access-point mode
SW_PIN=29

# initial state of switch is unknown
prev_state="unknown"

# setup pin as input with internal pull up
gpio mode $SW_PIN in
gpio mode $SW_PIN up

while true; do
	curr_state=$(gpio read $SW_PIN)
	
	# check if switch changed state
	if [ $curr_state != $prev_state ]; then
		if [ $curr_state == "1" ]; then
			echo "Configure as end point"
			# commands to setup WiFi as end point...
		else
			echo "Configure as access point"
			# commands to setup WiFi as access point...
		fi
	fi
	
	# store current state for next time
	prev_state=$curr_state

	# be nice to CPU and only update periodically
	sleep 5;
done

I run this script as a background service at startup so that the configuration switch can work even when the Pi is completely headless.

-Dan


Load Comments