1st Exercise
// Serial port object
let port;
// Latest sensor value
let sensorVal = 0;
function setup() {
createCanvas(400, 300);
background(220);
// Create the serial connection object
port = createSerial();
// If a port was used before, auto-reconnect
let used = usedSerialPorts();
if (used.length > 0) {
port.open(used[0], 9600);
}
}
function draw() {
background(220);
// Read one line of text until newline "\n"
let str = port.readUntil("\n");
// Make sure we actually received something
if (str.length > 0) {
// Convert the string into an integer
let val = int(str.trim());
// Map sensor value (0–1023) to screen X position (0–400)
let x = map(val, 0, 1023, 0, width);
// Draw a circle at mapped position
ellipse(x, height / 2, 40, 40);
} else {
// If empty data is received, print it for debugging
console.log("Empty:", str);
}
}
Arduino Code:
const int sensor=A2;
int sensorValue;
void setup() {
// put your setup code here, to run once:
pinMode(sensor,INPUT);
Serial.begin(9600);
// while (Serial.available() <= 0) {
Serial.println(0); // send a starting message
}
void loop() {
// put your main code here, to run repeatedly:
sensorValue=analogRead(sensor);
delay(60);
Serial.println(sensorValue);
}