xxxxxxxxxx
55
let port;
let lastVal = 0;
let smoothVal = 0;
let minVal = 1023;
let maxVal = 0;
function setup() {
createCanvas(400, 400);
port = createSerial();
}
function draw() {
background(0);
// unsmoothed
noStroke();
fill(255, 0, 0);
ellipse(175, height - (lastVal - minVal) / (maxVal - minVal) * height, 25, 25);
// smoothed
fill(0, 0, 255);
ellipse(225, height - (smoothVal - minVal) / (maxVal - minVal) * height, 25, 25);
let received = port.readUntil("\n");
if (received) {
//console.log(received);
lastVal = parseInt(received);
// reject values that are either to low or too high
// to be plausible
if (99 < lastVal && lastVal < 1024) {
if (lastVal < minVal) {
minVal = lastVal;
console.log('Saw new minimum value: ', minVal);
}
if (lastVal > maxVal) {
maxVal = lastVal;
console.log('Saw new maximum value: ', maxVal);
}
// general formula:
smoothVal = smoothVal * 0.95 + lastVal * 0.05;
}
}
}
function mousePressed() {
if (!port.opened()) {
port.open('Arduino', 9600);
}
}