This tutorial will explain how you can connect your Microbit to a PC and receive serial data into your Javascript application.
Go to the editor - https://makecode.microbit.org/#editor
Add the bluetooth extension
Go to the cog in the top left and select about
Click on experiments- enable bluetooth console
Build your code. See example below. This will connect the bluetooth and send "hello" as a message to the pc.
Transfer the code by dragging and dropping via usb.
Connect via bluetooth - connect the microbit to a power supply and disconnect from computer
Go to the cog and connect device via bluetooth.
The mcrobit should show a tick to say connected
You are ready to start building the app.
Create a new folder
Set up a index.html with a basic html template
Create two js files
main.js
bluetooth.js
Include these in your index.html
In index.html create a button called "connect device" - run the function microBitConnect()
Test the application using live Server. Make sure you microbit is still connected to make code online for this to work.
Click the button.
Open the console of your app and you should see "hello" being printed as well as other connection information.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
</head>
<body>
<h1>Test Bluetooth</h1>
<button onclick="microBitConnect()">Connect Device</button>
<script src="bluetoothConnection.js"></script>
<script src="main.js"></script>
</body>
</html>
function microBitReceivedMessage(message) {
console.log(message)
}
This function will receive the message from the micro bit in conjunction with the Bluetooth code below. In this function you can process the message into meaningful data for your application
/*
This code is to connect an BLE UART microbit to p5.
API:
microBitConnect()
This function should be called by an user event, like mousePressed() https://p5js.org/reference/#/p5/mousePressed
or KeyPressed() https://p5js.org/reference/#/p5/keyPressed
microBitDisconnect()
This function disconnects the microbit from the device running the p5 sketch.
microBitWriteString("string")
Writes a text to the microbit
microBitReceivedMessage()
This is a function that is called when the microBit sends a message to the device running P5
*/
// https://lancaster-university.github.io/microbit-docs/resources/bluetooth/bluetooth_profile.html
// An implementation of Nordic Semicondutor's UART/Serial Port Emulation over Bluetooth low energy
console.log("test");
const UART_SERVICE_UUID = "6e400001-b5a3-f393-e0a9-e50e24dcca9e";
// Allows the micro:bit to transmit a byte array
const UART_TX_CHARACTERISTIC_UUID = "6e400002-b5a3-f393-e0a9-e50e24dcca9e";
// Allows a connected client to send a byte array
const UART_RX_CHARACTERISTIC_UUID = "6e400003-b5a3-f393-e0a9-e50e24dcca9e";
let uBitDevice;
let rxCharacteristic;
function start() {
microBitConnect()
}
async function microBitWriteString(string) {
if (!rxCharacteristic) {
return;
}
try {
let encoder = new TextEncoder();
rxCharacteristic.writeValue(encoder.encode(string));
} catch (error) {
console.log(error);
}
}
async function microBitConnect() {
try {
console.log("Requesting Bluetooth Device...");
uBitDevice = await navigator.bluetooth.requestDevice({
filters: [{ namePrefix: "BBC micro:bit" }],
optionalServices: [UART_SERVICE_UUID]
});
console.log("Connecting to GATT Server...");
const server = await uBitDevice.gatt.connect();
console.log("Getting Service...");
const service = await server.getPrimaryService(UART_SERVICE_UUID);
console.log("Getting Characteristics...");
const txCharacteristic = await service.getCharacteristic(
UART_TX_CHARACTERISTIC_UUID
);
txCharacteristic.startNotifications();
txCharacteristic.addEventListener(
"characteristicvaluechanged",
onTxCharacteristicValueChanged
);
rxCharacteristic = await service.getCharacteristic(
UART_RX_CHARACTERISTIC_UUID
);
} catch (error) {
console.log(error);
}
}
function microBitDisconnect() {
if (!uBitDevice) {
return;
}
if (uBitDevice.gatt.connected) {
uBitDevice.gatt.disconnect();
console.log("Disconnected");
}
}
function onTxCharacteristicValueChanged(event) {
let receivedData = [];
for (var i = 0; i < event.target.value.byteLength; i++) {
receivedData[i] = event.target.value.getUint8(i);
}
const receivedString = String.fromCharCode.apply(null, receivedData);
if (typeof microBitReceivedMessage !== 'undefined') {
microBitReceivedMessage(receivedString);
} else {
console.log("microBitReceivedMessage is not defined")
}
console.log(receivedString);
}