xxxxxxxxxx
46
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");
if (str.length > 0) {
background(220);
text(str, 10, height-20);
let c = map( str, 0, 1024, 0, width);
circle(width/2, height/2, c);
}
// 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();
}
}