jones5112
Posts: 16
Joined: Fri Feb 01, 2019 4:27 am

Toggling WiFi via hardware

Sat May 18, 2019 12:35 pm

Hi guys,

I've done a fair bit of googling but I can't seem to find a solid answer.
I want to add a switch to my Pi3b and Pi zero that turns the wifi on and off, similar to what was on older style laptops.
My pi runs headless and I'd like the ability to connect to it without it broadcasting a wifi network all the time

Can this be done with a dt-overlay style command?
All the articles and sites I find talk about permanently disabling wifi, I just need to be able to toggle it.

User avatar
bensimmo
Posts: 4068
Joined: Sun Dec 28, 2014 3:02 pm
Location: East Yorkshire

Re: Toggling WiFi via hardware

Sat May 18, 2019 1:56 pm

Try rfkill with block/unblock to soft block it
Which is what I think desktop taskbar icon does.

klricks
Posts: 6441
Joined: Sat Jan 12, 2013 3:01 am
Location: Grants Pass, OR, USA
Contact: Website

Re: Toggling WiFi via hardware

Sat May 18, 2019 3:13 pm

Turn WIFI off:

Code: Select all

wpa_cli -i wlan0 disconnect
Turn WIFI back on:

Code: Select all

wpa_cli -i wlan0 reconnect
Also this may be useful:

Code: Select all

wpa_cli -i wlan0 status
Unless specified otherwise my response is based on the latest and fully updated Raspbian Buster w/ Desktop OS.

klricks
Posts: 6441
Joined: Sat Jan 12, 2013 3:01 am
Location: Grants Pass, OR, USA
Contact: Website

Re: Toggling WiFi via hardware

Sat May 18, 2019 4:33 pm

FYI the commands for rfkill are:

WIFI:

Code: Select all

rfkill block 0
rfkill unblock 0
For BT:

Code: Select all

rfkill block 1
rfkill unblock 1
Status:

Code: Select all

rfkill list
Unless specified otherwise my response is based on the latest and fully updated Raspbian Buster w/ Desktop OS.

jones5112
Posts: 16
Joined: Fri Feb 01, 2019 4:27 am

Re: Toggling WiFi via hardware

Sat May 18, 2019 9:44 pm

Thanks All I'll see what I can come up with!

jones5112
Posts: 16
Joined: Fri Feb 01, 2019 4:27 am

Re: Toggling WiFi via hardware

Wed Jun 26, 2019 1:27 am

Okay think I've sorted this out.
So I've got a python script running, I tried it with the rfkill commands and that worked okay for the Wifi signal. However it did not always restart the Access point, the main reason why I needed this.
So my script now simply starts and stops the hostapd service

Code: Select all

#!/usr/local/bin/python

import sys
import time
import os
import RPi.GPIO as IO

IO.setmode(38, IO.IN, pull_up_down=IO.PUD_UP)

try: 
		while True:
				button_state=IO.input(38)
				if button_state==False:
					os.system('systemctl start hostapd')
					time.sleep(2)
				
				else:
					os.system('systemctl stop hostapd')
					time.sleep(2)
except:
	IO.cleanup()

Seems to work fine for me, apologies for my poor coding skills but hopefully this might help someone.

Return to “Advanced users”