xxxxxxxxxx
23
let serial; // serial port object
let distance = 0; // variable to store distance measured by the ultrasonic sensor
function setup() {
createCanvas(400, 400);
serial = new p5.SerialPort(); // create new serial port object
serial.open("/dev/tty.usbmodem11301"); // replace with the serial port number of your Arduino board
serial.on("data", getData); // call getData function when data is received from the serial port
}
function getData() {
let data = serial.readStringUntil('\n'); // read data from serial port until newline character
if (data) { // if data is not empty
distance = parseInt(data); // convert data to integer and store in distance variable
}
}
function draw() {
background(220);
let size = map(distance, 0, 100, 50, 200); // map distance values to ellipse size
ellipse(width/2, height/2, size, size); // draw ellipse in the center of the canvas
}