Skip to content
 
 

Latest commit

 

History

85 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

  • 🔌 Wireless Connection - Connect micro:bit via Bluetooth Low Energy
  • 📊 Sensor Access - Read accelerometer, temperature, compass, and button states
  • 💡 LED Control - Display patterns and scrolling text on the 5×5 LED matrix
  • 💬 UART Communication - Bidirectional serial communication for custom data exchange
  • 🎨 Framework Friendly - Works seamlessly with p5.js and vanilla JavaScript
  • 🚀 Zero Dependencies - Pure JavaScript, no external libraries required

🎯 Use Cases

  • Physical Computing Projects - Create interactive installations and games
  • Educational Tools - Teach programming with visual feedback
  • IoT Prototypes - Build sensor-based web applications
  • Data Visualization - Display real-time sensor data in the browser

🚀 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:

  • Accelerometer Service - 3-axis motion sensing
  • Magnetometer Service - Compass and raw magnetic data
  • Button Service - A and B button states
  • Temperature Service - On-board temperature sensor
  • LED Service - 5×5 LED matrix control
  • IO Pin Service - GPIO access (partial support)
  • UART Service - Serial communication (Nordic UART Service)

References

🤝 Contributing

Contributions are welcome! Whether it's:

  • 🐛 Bug reports and fixes
  • ✨ New features and examples
  • 📝 Documentation improvements
  • 💡 Ideas and suggestions

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

About

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

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages