Web BLE detect

Updated on 18 November 2022
dev board Adafruit Feather Bluefruit
chip nRF52
features BLE
This tutorial is more than 1 year old. If the steps below do not work, then please check the latest versions and the documentations of the individual tools used.

Before starting

Dependancies

Ensure the following dependancies are downloaded and available:

Pre-requisites

Try these simpler or similar examples:

Buy the components

Code

Download code web-ble-detect.ino
#include <bluefruit.h>

void setup() {
  Serial.begin(115200);
  delay(500);
  Serial.println("Start!");

  Bluefruit.begin();
  Bluefruit.setName("Palm");

  startAdv();
}

void loop() { }

void startAdv(void) {
  Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE);
  Bluefruit.Advertising.addTxPower();
  Bluefruit.Advertising.addName();
  Bluefruit.Advertising.restartOnDisconnect(true);
  Bluefruit.Advertising.setInterval(32, 244);
  Bluefruit.Advertising.setFastTimeout(30);
  Bluefruit.Advertising.start(0);
}

Makefile

BOARD?=adafruit:nrf52:feather52832
PORT?=/dev/tty.SLAB_USBtoUART

.PHONY: default lint all flash clean

default: lint all flash clean

lint:
	cpplint --extensions=ino --filter=-legal/copyright *.ino

all:
	arduino-cli compile --fqbn $(BOARD) ./

flash:
	adafruit-nrfutil dfu genpkg --dev-type 0x0052 --application ./.*.hex dfu-package.zip
	adafruit-nrfutil dfu serial --package dfu-package.zip -p $(PORT) -b 115200

clean:
	rm -f .*.elf
	rm -f .*.hex
	rm -f *.zip

serve:
	echo "Open Chrome browser at http://localhost:8000/web-ble-detect.html"
	python -m SimpleHTTPServer 8000

Serial console

Serial output from the firmware.

Web BLE detect serial console

Browser console

Open the browser developer console.

Web BLE detect browser

Description

Connect to a BLE device with a given device name and display some device info in the Chrome browser console.

Ensure the browser side of the code is also implemented with web-ble-detect.html.

Download code View demo

<form>
  <button>Connect with BLE device</button>
</form>

<script>
  var deviceName = 'Palm'

  function isWebBluetoothEnabled() {
    if (!navigator.bluetooth) {
      console.log('Web Bluetooth API is not available in this browser!')
      return false
    }

    return true
  }

  function getDeviceInfo() {
    let options = {
      // acceptAllDevices: true // Option to accept all devices
      "filters": [
        { "name": deviceName }
      ]
    }

    console.log('Requesting Bluetooth Device...')
    navigator.bluetooth.requestDevice(options).then(device => {
      console.log('> Name: ' + device.name)
    }).catch(error => {
      console.log('Argh! ' + error)
    })
  }

  document.querySelector('form').addEventListener('submit', function(event) {
    event.stopPropagation()
    event.preventDefault()

    if (isWebBluetoothEnabled()) {
      getDeviceInfo()
    }
  })
</script>

References