Maker Pro
Raspberry Pi

Connecting Raspberry Pi 3 Wi-Fi Via Bluetooth

July 25, 2019 by Reginald Watson
Share
banner

Learn how to connect your Raspberry Pi 3 WiFi using an Android Phone through Bluetooth.

If you have been using a Raspberry Pi for a while, you might have come across several situations where you need to connect and reconnect the Wi-Fi network for the Pi. Doing so might require you to connect your Pi to a monitor, keyboard, and the whole shebang or to configure it directly on the memory card using another machine.

In this tutorial, I wanted to show you an easy way to configure the Wi-Fi network for your Raspberry Pi using just an Android phone through Bluetooth.

Using this technique, you no longer have to worry about switching between Wi-Fi networks on a headless Raspberry Pi.

Required Materials

To start, you’ll need:

Install Bluez On Raspbian

Enter the following commands in the Raspbian terminal step by step, starting with installing Bluez, a Python Bluetooth library:

$ sudo apt-get install python-bluez
how_to_configure_RPi_wifi_bluetooth_RW_MP_image1.png

Start the Bluetooth daemon in compatibility mode, edit /etc/systemd/system/dbus-org.bluez.service, by typing the command below:

$ sudo nano /etc/systemd/system/dbus-org.bluez.service

and modify the ExecStart param

ExecStart=/usr/lib/bluetooth/bluetoothd –C

how_to_configure_RPi_wifi_bluetooth_RW_MP_image2.png
how_to_configure_RPi_wifi_bluetooth_RW_MP_image3.png

Load serial port profile:

$ sudo sdptool add SP
how_to_configure_RPi_wifi_bluetooth_RW_MP_image4.png

Restart your Pi:

$ sudo reboot
how_to_configure_RPi_wifi_bluetooth_RW_MP_image5.png

Pairing Pi’s Bluetooth With Android

After rebooting, pair the Pi’s Bluetooth with your Android phone.

Pairing Bluetooth:

how_to_configure_RPi_wifi_bluetooth_RW_MP_image6.png

Turn on your phone's Bluetooth and pair your phone with the Raspberry Pi. Next, on your Pi, enter:

$ bluetoothctl
 power on
 discoverable on
 scan on

Your phone will appear in the list of available devices. Take note of your phone’s address.

trust <PHONE_ADDRESS>

pair <PHONE_ADDRESS>

how_to_configure_RPi_wifi_bluetooth_RW_MP_image7.png

To exit the Bluetooth ctl, enter the quit command:

quit

You can also skip the above setup if you find you can easily set up Bluetooth using the UI of Raspbian.

how_to_configure_RPi_wifi_bluetooth_RW_MP_image8.png
how_to_configure_RPi_wifi_bluetooth_RW_MP_image9.png
how_to_configure_RPi_wifi_bluetooth_RW_MP_image10.png

After the Bluetooth pairing, add the Python script directly into Raspbian by typing the nano command and copying/pasting the source code:

$ sudo python run.py

You can also directly copy the run.py file here.

how_to_configure_RPi_wifi_bluetooth_RW_MP_image11.png

Next, you can run the script. But first make the script executable:

$ chmod +x run.py

To run:

$ sudo ./run.py

After executing this, now you need to open the android app. To do this, download and install the app using the .apk file here.

Select Raspberry Pi in the Bluetooth paired devices. Enter the SSID, PSK and hit the start configuration button. Within a few seconds, your Raspberry Pi’s Wi-Fi should connect, as shown in the images below.

how_to_configure_RPi_wifi_bluetooth_RW_MP_image12.png
how_to_configure_RPi_wifi_bluetooth_RW_MP_image13.png
how_to_configure_RPi_wifi_bluetooth_RW_MP_image14.png

To run this script on startup, edit /etc/rc.local and add:

(sleep 10;/path/to/script/./run.py)&

how_to_configure_RPi_wifi_bluetooth_RW_MP_image15.png

Source code (run.py)

#!/usr/bin/env python
import os
from bluetooth import *
from wifi import Cell, Scheme
import subprocess
import time
wpa_supplicant_conf = "/etc/wpa_supplicant/wpa_supplicant.conf"
sudo_mode = "sudo "
def wifi_connect(ssid, psk):
    # write wifi config to file
    cmd = 'wpa_passphrase {ssid} {psk} | sudo tee -a {conf} > /dev/null'.format(
            ssid=str(ssid).replace('!', '\!'),
            psk=str(psk).replace('!', '\!'),
            conf=wpa_supplicant_conf
        )
    cmd_result = ""
    cmd_result = os.system(cmd)
    print cmd + " - " + str(cmd_result)

    # reconfigure wifi
    cmd = sudo_mode + 'wpa_cli -i wlan0 reconfigure'
    cmd_result = os.system(cmd)
    print cmd + " - " + str(cmd_result)

    time.sleep(10)

    cmd = 'iwconfig wlan0'
    cmd_result = os.system(cmd)
    print cmd + " - " + str(cmd_result)

    cmd = 'ifconfig wlan0'
    cmd_result = os.system(cmd)
    print cmd + " - " + str(cmd_result)

    p = subprocess.Popen(['hostname', '-I'], stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)

    out, err = p.communicate()

    if out:
        ip_address = out
    else:
        ip_address = "<Not Set>"
    return ip_address

def ssid_discovered():
    Cells = Cell.all('wlan0')
    wifi_info = 'Found ssid : \n'
    for current in range(len(Cells)):
        wifi_info +=  Cells[current].ssid + "\n"
    wifi_info+="!"
    print wifi_info
    return wifi_info
def handle_client(client_sock) :
    # get ssid
    client_sock.send(ssid_discovered())
    print "Waiting for SSID..."
    ssid = client_sock.recv(1024)
    if ssid == '' :
        return

    print "ssid received"
    print ssid

    # get psk
    client_sock.send("waiting-psk!")
    print "Waiting for PSK..."
    psk = client_sock.recv(1024)
    if psk == '' :
        return

    print "psk received"
    print psk

    ip_address = wifi_connect(ssid, psk)
    print "ip address: " + ip_address
    client_sock.send("ip-address:" + ip_address + "!")
    return
try:
    while True:
        server_sock=BluetoothSocket( RFCOMM )
        server_sock.bind(("",PORT_ANY))
        server_sock.listen(1)

        port = server_sock.getsockname()[1]

        uuid = "815425a5-bfac-47bf-9321-c5ff980b5e11"
        advertise_service( server_sock, "RPi Wifi config",
                           service_id = uuid,
                           service_classes = [ uuid, SERIAL_PORT_CLASS ],
                           profiles = [ SERIAL_PORT_PROFILE ])


        print "Waiting for connection on RFCOMM channel %d" % port

        client_sock, client_info = server_sock.accept()
        print "Accepted connection from ", client_info

        handle_client(client_sock)

        client_sock.close()
        server_sock.close()

        # finished config
        print 'Finished configuration\n'
except (KeyboardInterrupt, SystemExit):
    print '\nExiting\n'

Author

Avatar
Reginald Watson

I love challenging myself by creating new projects using different microcontrollers to see what I can come up with.

Related Content

Comments


You May Also Like