xxxxxxxxxx
129
/*
This basic code aims to control the LED (on the nano 33 BLE) blinking rate using P5
When you press connect, wait till the console writes 'Characteristics found' to press the change button
*/
//The code needs to have following functions
/*
1 Function to connect (It should include have a callback function)
2 function to search the characteristics and assign
3 Function to read value (It should include a callback function)
4 Function to control the LED
5 Function to write a value to the characteristic (It should have a callback function)
6 And more.......
*/
//NOTE: the UUIDs should be in lower cases in when using P5
const ledControl1 = "B6D5146F-505A-4950-8B61-E977815F0587"; // our service
let ledControl = ledControl1.toLowerCase();
const led1 = "D6818D69-00EF-4A65-8804-F897676C7CCC"; //our characteristics
let led = led1.toLowerCase();
let ledChar; //variable to hold our characteristics
let MyBLE; //variable for our device
function setup()
{
MyBLE = new p5ble(); //creating our new BLE device
createCanvas(400, 400);//
const connectButton = createButton("CONNECT TO THE NANO BLE");//create a button to connect to device when pressed
connectButton.position(50, 50); //positioning
connectButton.mousePressed(ConnectDevice);//when the button is pressed connect
const ledButton = createButton("CHANGE THE BLINKING RATE");//create a button to change the blinking rate
ledButton.position(50, 150);// positioning
ledButton.mousePressed(changeBlinkRate);//when the button is pressed change the blinking rate
}
function draw()
{
background(220);
}
//function to search for characteristics
//passing error and characteristics
function findChararacteristics(error, characteristics)
{
if(error)//if there is an error
{
console.log("There might vbe and error connecting");
return; //stop
}
for(let i = 0; i < characteristics.length;i++)//searching for our characteristics
{
// if we find the characteristics
if(characteristics[i].uuid == led)
{
//assigning the found characteristics to variable declared
ledChar = characteristics[i];
}
}
if(!ledChar)// if the characteristic isn't found
{
console.log("Could not find the characteristic");
}
else
{
console.log("Characteristics found");
}
}
function ConnectDevice()
{
MyBLE.connect(ledControl, findChararacteristics);// connect to the device
}
//function to toggle the rate
function toggleRate(error, data)
{
if(error)
{
console.log("Sorry! An error occured");
return;
}
console.log("The LED is set to: ", data);
MyBLE.write(ledChar, !data, checkErrorWritingValues);
}
//function to check if there is an error writing to the BLE
function checkErrorWritingValues(error)
{
if(error)
{
console.log("Error changing the value of LED");
return;
}
else
{
console.log("Value changed successful");
}
}
//function to change the blinking rate
function changeBlinkRate(error)
{
if(!ledChar)
{
console.log("Something wrong happened");
return;
}
MyBLE.read(ledChar, toggleRate);
}