P5.js as a web-based language that can be used with Arduino to allow a fast exchange of information between Arduino and a website.
P5.js Mode in Processing
To connect with the serial we can either use serial.autoConnectAndOpenPreviouslyApprovedPort(serialOptions);
, to connect with already connected port or serial.connectAndOpen(portInfo, serialOptions);
, to open the port menu
serial.on
subscribes to the events of the Serial class and handles the proper communication between WebSerial API and Arduino.
serialWriteTextData()
and serialWriteNumberData()
uses serial.writeLine()
to write values to Arduino. Notice the extra “<“ and “>” signs, which mark the beginning and end of a message.
Alternative Method with IDE
Install VS Code : https://code.visualstudio.com/docs/setup/setup-overview
Follow the seteps in the video to properly setup p5.js in VS Code
Although p5.js is written in JavaScript and not Java like Processing, the p5.js implementation has an almost identical API. It is therefore very easy to translate existing Processing code into p5.js e.x similar to Processing, p5.js abstracts away much of the complexity of writing JavaScript and allows to focus solely on interactive graphics and visualisations.
For a communication between p5.js and Arduino, we will use WebSerial API, which enables the websites to communicate with peripherals connected to the computer. Currently, Web Serial only runs on Internet Explorer and Chrome, so to use it, you need to install Chrome (or a Chrome-based) browser. To check if your browser supports WebSerial open a console (cmd + option+ i on Mac or ctrl + alt + i on Windows) and type in:
await navigator.serial.requestPort();
If the browser supports it, you will see a pop-up window, where you can choose one of the ports with Arduino plugged in.
If everything works you are (almost) set! 🔥
BE CAREFUL! If you have Serial port monitor open the connection is going to break up.
P5.js to Arduino
Download this file, unzip it and open the folder in VS Code:
File → Open... → p5Arduino
Your screen should look like this:
Make sure that you include serial.js in the head or body of your index.html.
You can do it either locally:
<script src="serial.js"></script>
or using jsDelivr service:
<script src="https://cdn.jsdelivr.net/gh/makeabilitylab/p5js/_libraries/serial.js"></script>