xxxxxxxxxx
62
let sensorValue = 0; // Variable to store sensor data
function setup() {
createCanvas(640, 480);
textSize(18);
if (!serialActive) {
setUpSerial(); // Start serial communication with Arduino
}
}
function draw() {
// Set the background to dark blue and purple hues based on the sensor value
background(map(sensorValue, 0, 1023, 50, 75), 0, map(sensorValue, 0, 1023, 100, 150));
// Map the sensor value to control the ellipse's horizontal position
let ellipseX = map(sensorValue, 0, 1023, 0, width);
// Draw the ellipse in the middle of the screen
fill(255); // White ellipse for contrast
ellipse(ellipseX, height / 2, 50, 50);
// Display connection status
fill(255); // White text for readability
if (!serialActive) {
text("Press Space Bar to select Serial Port", 20, 30);
} else {
text("Connected", 20, 30);
// Display the current sensor value
text("Sensor Value = " + str(sensorValue), 20, 50);
}
}
function keyPressed() {
if (key === " ") {
setUpSerial(); // Start the serial connection when the spacebar is pressed
}
}
// This function is called by the web-serial library with each new line of data
function readSerial(data) {
if (data != null) {
// Parse the sensor value from the Arduino
sensorValue = int(trim(data));
}
}
//ARDUINO CODE
//int sensorPin = A0; // Sensor connected to A0
//void setup() {
// Serial.begin(9600); // Start serial communication
//}
//void loop() {
// int sensorValue = analogRead(sensorPin); // Read sensor value
// Serial.println(sensorValue); // Send the value to p5.js
// delay(10); // Small delay to avoid overwhelming the serial buffer
//}