Welcome to the JavaScript (JS) Web Bluetooth API tutorial! This comprehensive guide will help you understand and use the Web Bluetooth API, a powerful tool for connecting JavaScript to Bluetooth devices. Let's get started!
The Web Bluetooth API is a JavaScript API that allows web apps to communicate with Bluetooth Low Energy (BLE) devices. This opens up a world of possibilities for IoT projects, smart devices, and more!
Before diving into code examples, let's make sure you have the necessary setup:
Here's a simple example of connecting to a BLE device using the Web Bluetooth API:
if ('BluetoothAdapter' in window && 'BluetoothDevice' in window) {
navigator.bluetooth.requestDevice({ filters: [] })
.then(device => device.gatt.connect())
.then(server => console.log('Connected to BLE device.'))
.catch(error => console.log('Error connecting: ', error));
} else {
console.log('Web Bluetooth API is not supported in this browser.');
}Let's break this code down:
navigator.bluetooth.requestDevice() method. The filters array can be used to specify the type of device you're looking for.device.gatt.connect() method.š” Pro Tip: Remember to add error handling to your code to ensure a smooth user experience.
After connecting to a BLE device, you can access its services and characteristics (properties) to read or write data. Here's an example of reading from a characteristic:
server.getPrimaryService('uuid_of_the_service')
.then(service => service.getCharacteristic('uuid_of_the_characteristic'))
.then(characteristic => characteristic.readValue())
.then(value => console.log('Characteristic value:', value))
.catch(error => console.log('Error reading characteristic:', error));In this example, we first get the primary service of the device using the getPrimaryService() method and then the characteristic using the getCharacteristic() method. Finally, we read the value from the characteristic using the readValue() method and log it to the console.
Writing to a characteristic follows a similar pattern:
const data = new Uint8Array([0x01, 0x02, 0x03]); // Example data
characteristic.writeValue(data)
.then(() => console.log('Data written to characteristic.'))
.catch(error => console.log('Error writing to characteristic:', error));In this example, we create an array data containing the data we want to write. Then, we write the data to the characteristic using the writeValue() method and log a success message if the write operation is successful.
Which method do you use to connect to a BLE device using the Web Bluetooth API?
That's it for this tutorial! I hope you enjoyed learning about the Web Bluetooth API and are ready to start building exciting IoT projects using JavaScript. Happy coding! š