I’ve created a sketch of multiple bubbles which change color randomly when they’re close to colliding and create a separate circle in the middle of the sketch. I’m controlling the x position of this specific circle by potentiometer. To communicate with the microcontroller serially, I used the P5.js serialport library and the P5.serialserver. Because the browser doesn’t have direct access to the serial port. But it can communicate with a server program on the computer that can exchange data .I’ve included the library to the html code.
<script language="javascript" type="text/javascript" src="p5.serialport.js"></script>
Alternatively, you can skip the installation of the p5.serialport.js file and use a copy from an online content delivery system by using the following line in your index.html instead:
<script language="javascript" type="text/javascript" src="https://cdn.jsdelivr.net/npm/p5.serialserver@0.0.28/lib/p5.serialport.js"></script>
The p5.js Sketch
To start off, the programming environment needs to know what serial ports are available in the operating system. On the sketch file I’ve added this code.
Serial Events
JavaScript, the language on which P5.js is based, relies heavily on events and callback functions. An event is generated by the operating system when something significant happens, like a serial port opening, or new data arriving in the port. In the sketch, I wrote a callback function to respond to that event. The serialport library uses events and callback functions as well. It can listen for the following serialport events:
list – the program asks for a list of ports.
connected – when the sketch connects to a webSocket-to-serial server
open – a serial port is opened
close – a serial port is closed
data – new data arrives in a serial port
error – something goes wrong.
I’m already using a callback for the ‘list’ event in the code right I’ve set a callback for the ‘list’ event, then I called it with serial.list(). Generally, I should set my callbacks before I use them like this.
To use the rest of the serialport library’s events, I need to set callback functions for them as well. So, I’veadded a new global variable called portName and initialize it with the name of your serial port. Then change your setup() function to include callbacks for open, close, and error like so.
The function that matters the most, though, is serialEvent(), the one that responds to new data. Each time a new byte arrives in the serial port, this function is called. Lastly, I made serialEvent() do some work. I’ve added a new global variable at the top of my sketch called inData like so:
var
serial;
var
portName = '/dev/cu.usbmodem1421'; //
var
inData;
The sensor value onscreen changes as I turn your potentiometer.