xxxxxxxxxx
38
let serial; // Variable to hold an instance of the serialport library
let latestData = "waiting for data"; // You will receive data here
function initiateSerial() {
// Example to activate serial communication; adapt based on your actual use case
isSerialActive = true; // Set isSerialActive to true
// Example: serial = new p5.SerialPort(); serial.open('COM3'); // You would need the p5.serialport library
}
function setup() {
createCanvas(400, 300);
// serial = new p5.SerialPort(); // Make a new instance of the serialport library
serial.on('data', serialEvent); // Callback for when new data arrives
serial.open('/dev/tty.usbmodem101'); // Change this to your Arduino port
}
function draw() {
background(255);
fill(50);
textSize(16);
textAlign(CENTER);
text("Distance: " + latestData + " cm", width / 2, height / 2);
if (parseInt(latestData) < 10) {
fill(255, 0, 0);
} else {
fill(0, 255, 0);
}
ellipse(width / 2, height / 2 + 30, 50, 50); // Display a circle that changes color based on distance
}
function serialEvent() {
let dataString = serial.readLine(); // Read the serial data
trim(dataString); // Trim whitespace
if (!dataString) return; // If the data is incomplete, return
latestData = dataString; // Update the data
}