xxxxxxxxxx
76
let rVal = 0;
let potentiometerInput = 0;
let circleX;
function setup() {
createCanvas(640, 480);
textSize(18);
circleX = width/2;
}
function draw() {
// one value from Arduino controls the background's red color
background(255);
// the other value controls the text's transparency value
if (!serialActive) {
text("Press Space Bar to select Serial Port", 20, 30);
} else {
text("Connected", 20, 30);
// Print the current values
text('potentiometerInput = ' + str(potentiometerInput), 20, 70);
}
//Draws the circle
circle(circleX,height/2,100);
}
function keyPressed() {
if (key == " ") {
// important to have in order to start the serial connection!!
setUpSerial();
}
}
// This function will be called by the web-serial library
// with each new line of data. The serial library reads
// the data until the newline and then gives it to us through
// this callback function
function readSerial(data) {
////////////////////////////////////
//READ FROM ARDUINO HERE
////////////////////////////////////
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
// We take the string we get from Arduino and explicitly
// convert it to a number by using int()
// e.g. "103" becomes 103
potentiometerInput = int(fromArduino[0]);
//Maps the potentiometer input value to the width of the canvas.
circleX = map(potentiometerInput,0,1023,0,width);
}
let sendToArduino = "\n";
writeSerial(sendToArduino);
}
}