xxxxxxxxxx
93
//This code aims to tracker the button status on a Nano BLE
const track = "44E1F33C-0AB5-4288-A3A2-1F2AE16A3AE1"; //tracking service
const trackButton1 = "5D5DAE3C-2D66-4117-A2AD-9800CA0C9208";//characteristic to be tracked
//convert the UUIDs to lower case
let tracker = track.toLowerCase();
let trackButton = trackButton1.toLowerCase();
let BleDevice = new p5ble();//our 'device'
let buttonStatus;//variable to track the status
let button; //this will be used keep the found characteristics
function setup()
{
createCanvas(400, 400);
const connectButton = createButton("CONNECT TO DEVICE");//creating a button to connect to the BLE device
connectButton.position(50, 50);
connectButton.mousePressed(connectToDevice);//when the button on P5 is pressed, connect to the device
const trackingButton = createButton("TRACK BUTTON STATUS");//create a button to track the status of the button on the Board
trackingButton.position(50, 200);
trackingButton.mousePressed(readValue);
}
function draw()
{
background(220);
if(buttonStatus !== undefined)
{ text("Button Status is: ",50, 250);
text(Number(buttonStatus), 50, 300);
if(buttonStatus)
{
background(255, 0, 255);
}
else
{
background(230, 255, 1);
}
}
}
//function to connect to to the device
function connectToDevice()
{
BleDevice.connect(tracker, findChar);//connect and find characteristics
}
//function to search for characteristics
//this function takes in an array of characteristics and search for what is needed
function findChar(error, characteristics)
{
if(error)//if an erros occurs
{
console.log("This error occured: ", error);
return;
}
for(let i = 0; i < characteristics.length; i++)
{
if(characteristics[i].uuid == trackButton)//if button tracker is found
{
button = characteristics[i];
console.log("Button tracker found");
}
}
if(!button)//if the button tracker is not found
{
console.log("Button Tracker Not Found");
}
}
//function to read value
function readValue()
{
if(!button)//if
{
console.log("Connection error");
return;
}
BleDevice.read(button, checkValue);
}
//function to check value
function checkValue(error, value)
{
if(error)
{
console.log("This error occured: ", error)
return;
}
buttonStatus = value;
console.log("Button is set to: ", Number(value));
}