xxxxxxxxxx
58
/*
Control the position of the ellipse on the screen through an Arduino analog sensor, such as a potentiometer.
Arduino code:
https://github.com/vsharkovski/nyuad-coursework/blob/main/introim/arduino/pot-ellipse/pot-ellipse.ino
*/
let potPosition = 0;
let currentX = 0;
function setup() {
createCanvas(640, 480);
textSize(18);
}
function draw() {
background(0);
fill(255);
ellipseMode(CENTER);
currentX = map(potPosition, 0, 1023, 0, width);
if (!serialActive) {
text("Press Space Bar to select Serial Port", 20, 30);
} else {
text("Connected", 20, 30);
ellipse(currentX, height / 2, 50, 50);
// Print the current value.
text("x = " + str(currentX), 20, 50);
}
}
function keyPressed() {
if (key == " ") {
setUpSerial();
}
}
function readSerial(data) {
if (data != null) {
// Make sure there is actually a message.
// Split the message.
let fromArduino = split(trim(data), ",");
// If the right length, then proceed.
if (fromArduino.length == 1) {
// Only store values here.
// Do everything with those values in the main draw loop.
potPosition = int(fromArduino[0]);
}
// Send to Arduino.
let sendToArduino = "1\n";
writeSerial(sendToArduino);
}
}