To create the script type the command below in the following directory /home/pi/Script/. Copy and paste the WifiBluetooth.py code below and save and exit.
Code: Select all
sudo nano WifiBluetooth.py
Code: Select all
"""
Before running the script please:
a) Install the following packages:
sudo apt-get install python-gpiozero
sudo apt-get install rfkill
b) Define GPIOs lines in global variables
Running the script in command line:
python WifiBluetooth.py
Running script automatically on boot:
Make and add python script to this directory: /home/pi/Script/
sudo nano /etc/rc.local
Add this line before exit 0:
python /home/pi/Script/WifiBluetooth.py &
Save, exit and reboot
"""
import subprocess
import time
from gpiozero import Button
from signal import pause
# Global viariables
# -----------------------------
# Define button GPIOs
button_bt = Button(23, bounce_time = .3)
button_wifi = Button(24, bounce_time = .3)
button_bt_status = True
button_wifi_status = True
# -----------------------------
def button_bt_pressed():
global button_bt_status
print("Bluetooth button is pressed")
button_bt_status = not button_bt_status
if (button_bt_status == True):
print("Turning on bluetooth")
subprocess.Popen("sudo rfkill unblock bluetooth", shell=True)
elif (button_bt_status == False):
print("Turning off bluetooth")
subprocess.Popen("sudo rfkill block bluetooth", shell=True)
def button_wifi_pressed():
global button_wifi_status
print("WiFi button is pressed")
button_wifi_status = not button_wifi_status
if (button_wifi_status == True):
print("Turning on wifi")
subprocess.Popen("sudo rfkill unblock wifi", shell=True)
elif (button_wifi_status == False):
print("Turning off wifi")
subprocess.Popen("sudo rfkill block wifi", shell=True)
button_wifi_pressed()
button_bt_pressed()
# Attach user defined functions to buttons press event
button_bt.when_pressed = button_bt_pressed
button_wifi.when_pressed = button_wifi_pressed
pause()