xxxxxxxxxx
80
var serial;
var bg = 0;
function setup() {
// Instantiate our SerialPort object
serial = new p5.SerialPort();
createCanvas(400, 400);
// Let's list the ports available
var portlist = serial.list();
// Assuming our Arduino is connected, let's open the connection to it
// Change this to the name of your arduino's serial port
serial.open("/dev/cu.usbmodem1441");
// Register some callbacks
// When we connect to the underlying server
serial.on('connected', serverConnected);
// When we get a list of serial ports that are available
serial.on('list', gotList);
// When we some data from the serial port
serial.on('data', gotData);
// When or if we get an error
serial.on('error', gotError);
// When our serial port is opened and ready for read/write
serial.on('open', gotOpen);
}
// We are connected and ready to go
function serverConnected() {
print("We are connected!");
}
// Got the list of ports
function gotList(thelist) {
// theList is an array of their names
for (var i = 0; i < thelist.length; i++) {
// Display in the console
print(i + " " + thelist[i]);
}
}
// Connected to our serial device
function gotOpen() {
print("Serial Port is open!");
}
// Ut oh, here is an error, let's log it
function gotError(theerror) {
print(theerror);
}
// There is data available to work with from the serial port
function gotData() {
var currentString = serial.readStringUntil("\r\n");
if (currentString){
console.log(currentString);
bg = int(currentString);
}
}
// Methods available
// serial.read() returns a single byte of data (first in the buffer)
// serial.readChar() returns a single char 'A', 'a'
// serial.readBytes() returns all of the data available as an array of bytes
// serial.readBytesUntil('\n') returns all of the data available until a '\n' (line break) is encountered
// serial.readString() retunrs all of the data available as a string
// serial.readStringUntil('\n') returns all of the data available as a tring until a (line break) is encountered
// serial.last() returns the last byte of data from the buffer
// serial.lastChar() returns the last byte of data from the buffer as a char
// serial.clear() clears the underlying serial buffer
// serial.available() returns the number of bytes available in the buffer
function draw() {
background(bg);
}