microbit-webble-p5js

A javascript library to interact with BBC micro:bit using web bluetooth API

View the Project on GitHub wongfei2009/microbit-webble-p5js

ubitwebble.js

๐ŸŽฎ A lightweight JavaScript library for connecting BBC micro:bit to web browsers via Web Bluetooth

Control your micro:bit directly from the browser! Create interactive web applications using the micro:bitโ€™s sensors, buttons, LED matrix, and UART communicationโ€”no cables required.

License: LGPL v2.1 Web Bluetooth API

โœจ Features

๐ŸŽฏ Use Cases

๐Ÿš€ Quick Start

1. Upload Firmware

Flash this firmware to your micro:bit to enable Bluetooth services.

2. Include Library

<script src="ubitwebble.js"></script>

3. Connect and Control

// Create instance
const microBit = new uBitWebBluetooth();

// Connect to micro:bit
await microBit.searchDevice();

// Display a smiley face
const smile = [
  ['0', '0', '0', '0', '0'],
  ['0', '1', '0', '1', '0'],
  ['0', '0', '0', '0', '0'], 
  ['1', '0', '0', '0', '1'],
  ['0', '1', '1', '1', '0']
];
microBit.writeMatrixIcon(smile);

// Read accelerometer
microBit.onBleNotify(() => {
  const accel = microBit.getAccelerometer();
  console.log(`X: ${accel.x}, Y: ${accel.y}, Z: ${accel.z}`);
});

// Handle button presses
microBit.setButtonACallback(() => {
  console.log('Button A pressed!');
});

๐ŸŒ Browser Support

Browser Support Status Platform
Chrome 56+ โœ… Full Support Windows, Mac, Android, Linux
Edge (Chromium) โœ… Full Support Windows, Mac
Opera โœ… Full Support All platforms
Firefox โŒ Not Supported Awaiting Web Bluetooth implementation
Safari โŒ Not Supported iOS and macOS

Note: Web Bluetooth API requires HTTPS or localhost for security.

๐Ÿ“š Examples

Explore interactive demos that showcase the libraryโ€™s capabilities:

๐ŸŒ Live Demos

Try these examples directly in your browser (requires micro:bit with uploaded firmware):

Example Description Live Demo
Basic Read sensors, control LEDs, handle button presses Launch
3D Accelerometer Real-time 3D character controlled by micro:bit tilt Launch
p5.play Game Interactive game using micro:bit as controller Launch
UART Echo Text communication via serial/UART Launch
Light Controller Control brightness using UART light sensor data Launch

๐Ÿ’ป Run Locally

  1. Clone the repository:
    git clone https://github.com/wongfei2009/microbit-webble-p5js.git
    cd microbit-webble-p5js
    
  2. Start a local server:

    Using Python 3:

    python3 -m http.server 8000
    

    Or using Node.js:

    npx http-server -p 8000
    
  3. Open in browser:
    http://localhost:8000/examples/basic/
    http://localhost:8000/examples/accelerometer_3Dbox/
    http://localhost:8000/examples/p5play_example/
    http://localhost:8000/examples/uart_echotext/
    http://localhost:8000/examples/uart_lightsensor/
    

Why localhost? Web Bluetooth requires a secure context (HTTPS or localhost) for privacy and security.

๐Ÿ“– API Reference

Connection Management

searchDevice() / connectDevice()

Initiates Bluetooth device discovery and connection.

await microBit.searchDevice();

disconnectDevice()

Disconnects from the currently connected micro:bit.

microBit.disconnectDevice();

onConnect(callback)

Registers a callback for successful connection.

microBit.onConnect(() => {
  console.log('Connected to micro:bit!');
});

onDisconnect(callback)

Registers a callback for disconnection events.

microBit.onDisconnect(() => {
  console.log('Disconnected from micro:bit');
});

๐Ÿ”˜ Button Input

setButtonACallback(callback) / setButtonBCallback(callback)

Handles button press events.

microBit.setButtonACallback(() => {
  console.log('Button A pressed');
});

microBit.setButtonBCallback(() => {
  console.log('Button B pressed');
});

getButtonA() / getButtonB()

Returns current button state (0 = released, 1 = pressed).

const aPressed = microBit.getButtonA();

๐Ÿ“Š Sensor Data

getAccelerometer()

Returns accelerometer data as {x, y, z} in milli-g (ยฑ2000 range).

const accel = microBit.getAccelerometer();
console.log(`Tilt: X=${accel.x}, Y=${accel.y}, Z=${accel.z}`);

getTemperature()

Returns temperature in degrees Celsius.

const temp = microBit.getTemperature();
console.log(`Temperature: ${temp}ยฐC`);

getBearing()

Returns compass heading (0-360 degrees).

const heading = microBit.getBearing();
console.log(`Heading: ${heading}ยฐ`);

onBleNotify(callback)

Called whenever any BLE characteristic updates (sensors, buttons).

microBit.onBleNotify(() => {
  // Update UI with latest sensor values
  updateDisplay(microBit.getAccelerometer());
});

๐Ÿ’ก LED Matrix Control

writeMatrixIcon(matrix)

Displays a custom pattern on the 5ร—5 LED matrix.

const heart = [
  ['0', '1', '0', '1', '0'],
  ['1', '1', '1', '1', '1'],
  ['1', '1', '1', '1', '1'],
  ['0', '1', '1', '1', '0'],
  ['0', '0', '1', '0', '0']
];
microBit.writeMatrixIcon(heart);

writeMatrixText(text)

Displays scrolling text on the LED matrix.

microBit.writeMatrixText('Hello World!');

writeMatrixTextSpeed(speed)

Sets the scrolling speed (lower = faster).

microBit.writeMatrixTextSpeed(100);

๐Ÿ“ก UART Communication

writeUARTData(data) / sendSerial(data) / uBitSend(data)

Sends a string via UART (automatically appends newline).

microBit.writeUARTData('Hello micro:bit');
// Aliases:
microBit.sendSerial('Same thing');
microBit.uBitSend('Also works');

setReceiveUARTCallback(callback) / onReceiveUART(callback) / onReceiveSerial(callback)

Registers a callback for incoming UART data.

microBit.setReceiveUARTCallback((data) => {
  console.log('Received:', data);
});

๐Ÿ”ง GPIO (Experimental)

Note: GPIO pin control is currently in development.

writePin(pin, value)

Writes a value to a GPIO pin (implementation in progress).

readPin(pin)

Reads a value from a GPIO pin (implementation in progress).

๐ŸŽ“ Usage Examples

Example 1: Motion-Controlled Web App

const microBit = new uBitWebBluetooth();

document.getElementById('connectBtn').addEventListener('click', async () => {
  await microBit.searchDevice();
});

microBit.onConnect(() => {
  console.log('Ready!');
});

microBit.onBleNotify(() => {
  const accel = microBit.getAccelerometer();
  
  // Tilt to control
  const tiltX = map(accel.x, -1000, 1000, -45, 45);
  const tiltY = map(accel.y, -1000, 1000, -45, 45);
  
  // Update 3D object rotation
  object.rotation.x = tiltX;
  object.rotation.y = tiltY;
});

Example 2: Temperature Monitor

microBit.onBleNotify(() => {
  const temp = microBit.getTemperature();
  
  // Update display
  document.getElementById('temp').textContent = `${temp}ยฐC`;
  
  // Visual feedback on micro:bit
  if (temp > 25) {
    const hot = [
      ['1', '0', '1', '0', '1'],
      ['0', '1', '0', '1', '0'],
      ['1', '0', '1', '0', '1'],
      ['0', '1', '0', '1', '0'],
      ['1', '0', '1', '0', '1']
    ];
    microBit.writeMatrixIcon(hot);
  }
});

Example 3: Bidirectional Communication

// Send data to micro:bit
document.getElementById('sendBtn').addEventListener('click', () => {
  const message = document.getElementById('input').value;
  microBit.writeUARTData(message);
});

// Receive data from micro:bit
microBit.setReceiveUARTCallback((data) => {
  console.log('micro:bit says:', data);
  document.getElementById('output').textContent = data;
});

๐Ÿ› ๏ธ Technical Details

Bluetooth Services Used

The library utilizes these micro:bit Bluetooth Low Energy services:

References

๐Ÿค Contributing

Contributions are welcome! Whether itโ€™s:

Please feel free to open issues or submit pull requests.

๐Ÿ“„ License

This project is licensed under the GNU Lesser General Public License v2.1 (LGPL-2.1).

See LICENSE file for details.

๐Ÿ™ Acknowledgments


Made with โค๏ธ for makers, educators, and creative coders