xxxxxxxxxx
85
let distance = 0;
let pressure = 0;
let name = "";
let toArduino = "\n";
function setup() {
createCanvas(640, 480);
textSize(18);
// create input for user to enter name of cat
textBox = createInput();
inputBox.position((width-inputWidth)/2, height/2);
inputBox.size(inputWidth, inputHeight);
name = inputBox.value();
textFont(FuturaHeavy)
textSize(para)
fill(myPink);
text(name, width / 2, height / 2+h1+para);
// button to confirm the name of cat
sendButton = createButton("Send to Arduino");
sendButton.position(textBox.x + textBox.width + 10, textBox.y);
sendButton.mousePressed(nameCheck);
}
function draw() {
// one value from Arduino controls the background's red color
background(map(pressure, 0, 1023, 0, 255), 255, 200);
fill("black");
if (!serialActive) {
text("Press OPTION to select Serial Port", 20, 30);
} else {
text("Connected", 20, 30);
// Print the current values
text("Distance = " + str(distance), 20, 50);
text("Pressure = " + str(pressure), 20, 70);
}
name = textBox.value();
fill("pink");
text(name, width / 2, height / 2);
}
function keyPressed() {
if (keyCode == OPTION) {
// 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 == 2) {
// 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
distance = int(fromArduino[0]);
pressure = int(fromArduino[1]);
}
writeSerial(toArduino);
}
}
function nameCheck() {
// form message to send to arduino
toArduino = name + "\n";
}