xxxxxxxxxx
58
let port;
let connectBtn;
function setup() {
createCanvas(400, 400);
background(220);
port = createSerial();
// setup serial ports
let usedPorts = usedSerialPorts();
if (usedPorts.length > 0) {
port.open(usedPorts[0], 9600);
}
connectBtn = createButton("Disconnect");
connectBtn.position(width / 2 - connectBtn.width / 2, height - 40);
connectBtn.mousePressed(connectBtnClick);
}
function draw() {
// reads the incomming value
let str = port.readUntil("\n");
// split the string on the commas:
let values = split(str, ",");
if (values.length > 1) {
background(220);
// if there are 2 elements
// element 0 is the diameter
let cDiameter = map(values[0], 0, 1024, 0, width);
// element 1 is the color
let cColor = values[1];
fill(int(cColor));
circle(width / 2, height / 2, cDiameter);
// write the values on the screen
fill(0);
text(str, 10, height - 20);
}
// changes button label based on connection status
if (!port.opened()) {
connectBtn.html("_Connect_");
} else {
connectBtn.html("Disconnect");
}
}
function connectBtnClick() {
if (!port.opened()) {
port.open("Arduino", 9600);
} else {
port.close();
}
}