Heart Rate Monitor
Introduction
This activity demonstrates how to use a heart rate monitor. Many of you will do biosignal sensing in your projects, however, the same model we will learn here applies to object detection.
Materials
- Heart Rate Monitor
- Arduino, breadboard and jumper cables
- Processing.org and Arduino IDEs
Activity
Wire the Heart Rate Monitor Circuit
Wire your heart rate monitor like the following diagram. Be sure to be VERY aware of which pin is which and that you're using 3.3V logic.
Check, double-check, and triple-check your wiring before plugging in the Arduino power.
Install the SparkFun MAX3010x Pulse and Proximity Library
Go to Tools > Manage Libraries and search for SparkFun MAX3010 and click install on the SparkFun MAX3010x Pulse and Proximity Library.
Copy Arduino Code
Copy the following code into your Arduio IDE:
#include <Wire.h>
#include "MAX30105.h"
MAX30105 sensor;
// ------------------------------------
// Configuration
// ------------------------------------
const byte SENSOR_ADDRESS = 0x57;
const unsigned long BAUD_RATE = 115200;
const unsigned long REPORT_INTERVAL = 2000;
const unsigned long NO_DATA_WARNING = 1500;
const unsigned long INIT_RETRY_INTERVAL = 2000;
// ------------------------------------
// State and diagnostic counters
// ------------------------------------
bool sensorReady = false;
unsigned long lastInitAttempt = 0;
unsigned long lastReport = 0;
unsigned long lastSampleTime = 0;
unsigned long totalSamples = 0;
unsigned long samplesAtLastReport = 0;
unsigned long totalChecks = 0;
unsigned long maxCheckDuration = 0;
unsigned long lastCheckDuration = 0;
unsigned long lastIR = 0;
unsigned long lastRED = 0;
unsigned long lastLedToggle = 0;
bool ledState = false;
unsigned int consecutiveEmptyChecks = 0;
// ------------------------------------
// Initialize sensor
// ------------------------------------
bool initializeSensor() {
Serial.println("# INIT: starting MAX30102");
// Important: sensor.begin() initializes Wire
// and sets the selected I2C clock.
if (!sensor.begin(Wire, I2C_SPEED_STANDARD)) {
Serial.println("# ERROR: sensor.begin failed");
return false;
}
Serial.println("# INIT: sensor detected");
// LED brightness, averaging, mode,
// sample rate, pulse width, ADC range
sensor.setup(
60,
1,
2,
100,
411,
4096
);
sensor.setPulseAmplitudeRed(60);
sensor.setPulseAmplitudeIR(60);
sensor.clearFIFO();
Serial.println("# INIT: sensor configured");
Serial.println("# INIT: sampling at 100 Hz");
lastSampleTime = millis();
consecutiveEmptyChecks = 0;
maxCheckDuration = 0;
return true;
}
// ------------------------------------
// I2C acknowledgment diagnostic
// ------------------------------------
byte checkI2C() {
Wire.beginTransmission(SENSOR_ADDRESS);
// 0 = address acknowledged
// Nonzero = communication error
return Wire.endTransmission();
}
// ------------------------------------
// Diagnostic report
// ------------------------------------
void printDiagnostics() {
unsigned long now = millis();
unsigned long elapsed = now - lastReport;
unsigned long newSamples =
totalSamples - samplesAtLastReport;
float sampleRate = 0;
if (elapsed > 0) {
sampleRate = newSamples * 1000.0 / elapsed;
}
Serial.println("# ----------------------");
Serial.print("# UPTIME_MS: ");
Serial.println(now);
Serial.print("# TOTAL_SAMPLES: ");
Serial.println(totalSamples);
Serial.print("# SAMPLES_PER_SECOND: ");
Serial.println(sampleRate, 1);
Serial.print("# TOTAL_CHECKS: ");
Serial.println(totalChecks);
Serial.print("# LAST_CHECK_US: ");
Serial.println(lastCheckDuration);
Serial.print("# MAX_CHECK_US: ");
Serial.println(maxCheckDuration);
Serial.print("# EMPTY_CHECKS: ");
Serial.println(consecutiveEmptyChecks);
Serial.print("# LAST_IR: ");
Serial.println(lastIR);
Serial.print("# LAST_RED: ");
Serial.println(lastRED);
Serial.print("# TIME_SINCE_SAMPLE_MS: ");
Serial.println(now - lastSampleTime);
// Verify that the sensor still acknowledges
// its I2C address.
byte status = checkI2C();
Serial.print("# I2C_STATUS: ");
Serial.println(status);
if (status != 0) {
Serial.println("# WARNING: I2C communication error");
}
if (now - lastSampleTime > NO_DATA_WARNING) {
Serial.println("# WARNING: NO SENSOR DATA");
}
Serial.println("# ----------------------");
lastReport = millis();
samplesAtLastReport = totalSamples;
maxCheckDuration = 0;
}
// ------------------------------------
// Arduino setup
// ------------------------------------
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
Serial.begin(BAUD_RATE);
delay(1000);
Serial.println();
Serial.println("# ======================");
Serial.println("# UNO R4 MAX30102 DIAGNOSTIC");
Serial.println("# ======================");
Wire.begin();
Wire.setClock(100000);
// Uno R4 timeout behavior is core-specific.
Wire.setWireTimeout(25000, false);
Serial.println("# I2C initialized");
sensorReady = initializeSensor();
lastInitAttempt = millis();
lastReport = millis();
if (!sensorReady) {
Serial.println("# Waiting to retry initialization");
}
}
// ------------------------------------
// Main loop
// ------------------------------------
void loop() {
unsigned long now = millis();
// ----------------------------------
// Sensor not initialized
// ----------------------------------
if (!sensorReady) {
// Blink LED when initialization fails.
if (now - lastLedToggle >= 250) {
lastLedToggle = now;
ledState = !ledState;
digitalWrite(LED_BUILTIN, ledState);
}
if (now - lastInitAttempt >= INIT_RETRY_INTERVAL) {
lastInitAttempt = now;
sensorReady = initializeSensor();
if (sensorReady) {
Serial.println("# RECOVERED: sensor initialized");
lastReport = millis();
}
}
return;
}
// ----------------------------------
// Sensor acquisition
// ----------------------------------
// LED ON while inside sensor.check().
// If check() hangs, LED may stay ON.
digitalWrite(LED_BUILTIN, HIGH);
unsigned long checkStart = micros();
uint16_t newReadings = sensor.check();
lastCheckDuration = micros() - checkStart;
digitalWrite(LED_BUILTIN, LOW);
totalChecks++;
if (lastCheckDuration > maxCheckDuration) {
maxCheckDuration = lastCheckDuration;
}
if (newReadings == 0) {
consecutiveEmptyChecks++;
} else {
consecutiveEmptyChecks = 0;
}
// ----------------------------------
// Transmit red + infrared readings
// ----------------------------------
while (sensor.available()) {
unsigned long ir = sensor.getFIFOIR();
unsigned long red = sensor.getFIFORed();
lastIR = ir;
lastRED = red;
lastSampleTime = millis();
totalSamples++;
// Processing-compatible CSV:
// IR,RED
Serial.print(ir);
Serial.print(',');
Serial.println(red);
sensor.nextSample();
}
// ----------------------------------
// Periodic diagnostics
// ----------------------------------
if (millis() - lastReport >= REPORT_INTERVAL) {
printDiagnostics();
}
}
See the raw serial output
Open your serial monitor and see what the raw output from the Arduino looks like. It should look like this:
994,1822
1030,1832
1023,1834
1005,1809
1012,1813
Try playing with the monitor. How does the raw signal respond? What is the min and max?
Copy the Processing Code
Copy the following code into your Processing IDE:
import processing.serial.*;
import java.util.Arrays;
import java.util.ArrayList;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketTimeoutException;
Serial arduino;
DatagramSocket simulator;
final int BUFFER_SIZE = 2000;
final int SAMPLE_RATE = 100;
final float PREDICTION_SIGMA_SAMPLES = 8;
final int PARTICLE_COUNT = 120;
final float GRAPH_LEFT = 82;
final float GRAPH_RIGHT = 780;
final float GRAPH_TOP = 125;
final float GRAPH_BOTTOM = 340;
final float PANEL_LEFT = 810;
float[] raw = new float[BUFFER_SIZE];
int head = 0;
int count = 0;
// The primary window is the oscilloscope view. The secondary window is the
// trailing group of samples used by the selected filter.
int windowSize = 500;
int divisions = 5;
String[] filterNames = { "MIN", "MAX", "AVERAGE", "MEDIAN", "MODE" };
color[] filterColors = {
color(255, 190, 65), color(239, 111, 108), color(113, 210, 154),
color(179, 137, 255), color(255, 133, 204)
};
class FilterStage {
int type;
int window;
FilterStage(int type, int window) {
this.type = type;
this.window = window;
}
}
ArrayList<FilterStage> filterChain = new ArrayList<FilterStage>();
int selectedStage = -1;
float viewCenter = 0;
float viewRange = 4000;
boolean viewInitialized = false;
boolean autoScale = true;
boolean paused = false;
float autoLow = 0;
float autoHigh = 4000;
float currentIR = 0;
float currentRED = 0;
float signalLow = 0;
float signalHigh = 0;
int totalSamples = 0;
int previousSamples = 0;
int samplesPerSecond = 0;
int lastRateCheck = 0;
boolean serialMode = false;
String sourceName = "starting";
boolean draggingWindow = false;
boolean draggingFilter = false;
boolean draggingAlignment = false;
boolean draggingTolerance = false;
int alignmentType = 0;
int alignmentOffset = 0;
String[] alignmentNames = { "EQUAL", "MIN", "MAX", "AVERAGE", "MEDIAN", "MODE" };
float timingTolerance = 10;
int fixedPeakInterval = 100;
boolean particleFilterEnabled = false;
boolean showFilters = false;
boolean showAlignment = false;
boolean showPrediction = false;
float[] particleIntervals = new float[PARTICLE_COUNT];
float particleIntervalEstimate = 100;
long lastParticleDivision = -1;
int lastParticleConfig = 0;
float[] bayesPrediction = new float[0];
float[] bayesEvidence = new float[0];
float[] bayesPosterior = new float[0];
float[] bayesSignal = new float[0];
long capturedSamples = 0;
long lastBayesDivision = -1;
int lastBayesConfig = 0;
void setup() {
size(1180, 760);
frameRate(60);
startSimulatorReceiver();
connectSerialOrUseSimulator();
}
void startSimulatorReceiver() {
try {
simulator = new DatagramSocket(8765);
simulator.setSoTimeout(1);
}
catch (Exception error) {
println("Could not listen for the Python simulator: " + error.getMessage());
}
}
void connectSerialOrUseSimulator() {
String[] ports = Serial.list();
printArray(ports);
if (ports.length == 0) {
useSimulator("Python simulator on UDP 8765");
return;
}
int selected = -1;
for (int i = 0; i < ports.length; i++) {
String p = ports[i].toLowerCase();
if (p.indexOf("usb") >= 0 || p.indexOf("arduino") >= 0 || p.indexOf("acm") >= 0) {
selected = i;
break;
}
}
// macOS normally lists virtual Bluetooth ports even with no board attached.
// Treat those as "no Arduino" instead of opening a silent serial stream.
if (selected < 0) {
useSimulator("Python simulator on UDP 8765");
return;
}
try {
arduino = new Serial(this, ports[selected], 115200);
arduino.clear();
sourceName = ports[selected];
serialMode = true;
}
catch (RuntimeException error) {
println("Serial connection failed: " + error.getMessage());
useSimulator("Python simulator on UDP 8765");
}
}
void useSimulator(String reason) {
if (arduino != null) {
arduino.stop();
arduino = null;
}
serialMode = false;
sourceName = reason;
}
void draw() {
receiveSamples();
updateSampleRate();
background(19, 23, 30);
findSignalBounds();
drawHeader();
drawWaveform();
if (showAlignment) drawBeatWindow();
drawControlPanel();
}
void receiveSamples() {
if (!serialMode) {
receiveSimulatorSamples();
return;
}
int processed = 0;
while (arduino != null && processed < 150 && arduino.available() > 0) {
String line = arduino.readStringUntil('\n');
if (line == null) break;
processed++;
line = trim(line);
if (line.length() == 0) continue;
if (line.startsWith("#")) {
println(line);
continue;
}
String[] values = split(line, ',');
if (values.length != 2) continue;
try {
acceptSample(Float.parseFloat(values[0]), Float.parseFloat(values[1]));
}
catch (NumberFormatException error) {
// Ignore malformed or partially received lines.
}
}
}
void receiveSimulatorSamples() {
if (simulator == null) return;
for (int processed = 0; processed < 150; processed++) {
byte[] data = new byte[64];
DatagramPacket packet = new DatagramPacket(data, data.length);
try {
simulator.receive(packet);
parseSample(new String(packet.getData(), 0, packet.getLength()));
}
catch (SocketTimeoutException done) {
break;
}
catch (Exception error) {
println("Simulator receive error: " + error.getMessage());
break;
}
}
}
void parseSample(String line) {
String[] values = split(trim(line), ',');
if (values.length != 2) return;
try {
acceptSample(Float.parseFloat(values[0]), Float.parseFloat(values[1]));
}
catch (NumberFormatException error) {
// Ignore malformed or partially received lines.
}
}
void acceptSample(float ir, float red) {
currentIR = ir;
currentRED = red;
totalSamples++;
if (!paused) addSample(ir);
}
void updateSampleRate() {
if (millis() - lastRateCheck >= 1000) {
samplesPerSecond = totalSamples - previousSamples;
previousSamples = totalSamples;
lastRateCheck = millis();
}
}
int indexAt(int offset) {
return (head + offset + BUFFER_SIZE) % BUFFER_SIZE;
}
void addSample(float value) {
if (!viewInitialized) {
viewCenter = value;
viewInitialized = true;
}
raw[head] = value;
head = (head + 1) % BUFFER_SIZE;
count = min(count + 1, BUFFER_SIZE);
capturedSamples++;
}
int visibleCount() {
return min(count, windowSize);
}
float sampleFromOldest(int visibleIndex) {
int visible = visibleCount();
return raw[indexAt(visibleIndex - visible)];
}
void findSignalBounds() {
int visible = visibleCount();
if (visible == 0) {
signalLow = viewCenter - viewRange / 2;
signalHigh = viewCenter + viewRange / 2;
return;
}
signalLow = Float.MAX_VALUE;
signalHigh = -Float.MAX_VALUE;
for (int i = 0; i < visible; i++) {
float value = sampleFromOldest(i);
signalLow = min(signalLow, value);
signalHigh = max(signalHigh, value);
}
}
void drawWaveform() {
float left = GRAPH_LEFT;
float right = GRAPH_RIGHT;
float top = GRAPH_TOP;
float bottom = showAlignment ? GRAPH_BOTTOM : 650;
float low = viewCenter - viewRange / 2;
float high = viewCenter + viewRange / 2;
if (autoScale && visibleCount() > 1) {
float span = max(signalHigh - signalLow, 1);
low = signalLow - span * 0.10;
high = signalHigh + span * 0.10;
autoLow = low;
autoHigh = high;
}
fill(25, 31, 41);
noStroke();
rect(left, top, right - left, bottom - top, 8);
fill(218);
textAlign(LEFT, BASELINE);
textSize(14);
text("IR signal", left, top - 17);
fill(125, 139, 158);
text(windowSize + " samples • " + nf(windowSize / float(SAMPLE_RATE), 0, 2) + " seconds", left + 68, top - 17);
textSize(12);
textAlign(RIGHT, CENTER);
for (int i = 0; i <= 4; i++) {
float y = lerp(top, bottom, i / 4.0);
float value = lerp(high, low, i / 4.0);
stroke(55, 65, 79);
strokeWeight(1);
line(left, y, right, y);
fill(153, 166, 184);
text(nf(value, 0, 0), left - 8, y);
}
// Equal primary-window divisions make time intervals countable by hand.
textAlign(CENTER, TOP);
for (int i = 0; i <= divisions; i++) {
float x = lerp(left, right, i / float(divisions));
stroke(68, 79, 94);
line(x, top, x, bottom);
fill(130, 143, 161);
float samplesAgo = windowSize * (divisions - i) / float(divisions);
text(i == divisions ? "now" : "-" + nf(samplesAgo / SAMPLE_RATE, 0, 1) + " s", x, bottom + 9);
}
textAlign(LEFT, BASELINE);
int visible = visibleCount();
if (showFilters && visible > 0 && selectedStage >= 0 && selectedStage < filterChain.size()) {
int effectiveFilter = min(filterChain.get(selectedStage).window, visible);
float filterLeft = map(visible - effectiveFilter, 0, max(visible - 1, 1), left, right);
noStroke();
color selectedColor = filterColors[filterChain.get(selectedStage).type];
fill(red(selectedColor), green(selectedColor), blue(selectedColor), 26);
rect(filterLeft, top, right - filterLeft, bottom - top);
}
float[][] stages = buildFilterStages();
if (visible >= 2) {
clip((int)left, (int)top, (int)(right - left), (int)(bottom - top));
noFill();
stroke(65, 190, 245);
strokeWeight(1.7);
beginShape();
for (int i = 0; i < visible; i++) {
float x = map(i, 0, visible - 1, left, right);
float y = map(sampleFromOldest(i), low, high, bottom, top);
vertex(x, y);
}
endShape();
for (int stage = 0; stage < stages.length; stage++) {
noFill();
stroke(filterColors[filterChain.get(stage).type]);
strokeWeight(stage == stages.length - 1 ? 2.5 : 1.5);
beginShape();
for (int i = 0; i < visible; i++) {
float x = map(i, 0, visible - 1, left, right);
float y = map(stages[stage][i], low, high, bottom, top);
vertex(x, y);
}
endShape();
}
noClip();
}
fill(155, 169, 188);
textSize(13);
text("RAW", left, bottom + 52);
stroke(65, 190, 245);
strokeWeight(3);
line(left + 38, bottom + 47, left + 66, bottom + 47);
float legendX = left + 90;
for (int stage = 0; showFilters && stage < filterChain.size(); stage++) {
FilterStage filter = filterChain.get(stage);
fill(155, 169, 188);
String label = (stage + 1) + " " + filterNames[filter.type];
text(label, legendX, bottom + 52);
legendX += textWidth(label) + 9;
stroke(filterColors[filter.type]);
line(legendX, bottom + 47, legendX + 24, bottom + 47);
legendX += 42;
}
if (paused) {
noStroke();
fill(255, 200, 70, 235);
rect(right - 94, top + 16, 76, 30, 15);
fill(32, 36, 43);
textAlign(CENTER, CENTER);
textSize(12);
text("PAUSED", right - 56, top + 30);
textAlign(LEFT, BASELINE);
}
}
int beatWindowSize() {
return max(2, windowSize / divisions);
}
float[] latestSamples(int length) {
int available = min(count, length);
float[] result = new float[available];
for (int i = 0; i < available; i++) result[i] = raw[indexAt(i - available)];
return result;
}
float[] processedSamples(int desiredLength) {
int warmup = 0;
if (showFilters) {
for (FilterStage stage : filterChain) warmup += max(0, stage.window - 1);
}
int sourceLength = min(count, desiredLength + warmup);
float[] processed = latestSamples(sourceLength);
if (showFilters) {
for (FilterStage stage : filterChain) {
processed = applyFilter(processed, stage.type, stage.window);
}
}
int resultLength = min(desiredLength, processed.length);
float[] result = new float[resultLength];
arrayCopy(processed, processed.length - resultLength, result, 0, resultLength);
return result;
}
float[] getBeatWindow() {
int beatSize = beatWindowSize();
int displaySize = showPrediction ? beatSize * 2 : beatSize;
float[] source = processedSamples(displaySize);
if (alignmentType == 0 || source.length < beatSize) return source;
int statisticType = alignmentType - 1;
int searchEnd = min(beatSize - 1, source.length - 1);
float target = statistic(source, 0, searchEnd, statisticType);
int featureIndex = 0;
float closest = abs(source[0] - target);
for (int i = 1; i <= searchEnd; i++) {
float distance = abs(source[i] - target);
if (distance < closest) {
closest = distance;
featureIndex = i;
}
}
return rotateSamples(source, featureIndex - alignmentOffset);
}
float[] mostRecentCompleteDivision(int size) {
int remainder = (int)(capturedSamples % size);
int required = size + remainder;
float[] history = processedSamples(required);
if (history.length < required) return new float[0];
float[] division = new float[size];
int start = history.length - remainder - size;
arrayCopy(history, start, division, 0, size);
return division;
}
void drawBeatWindow() {
float left = GRAPH_LEFT;
float right = GRAPH_RIGHT;
float top = 430;
float bottom = 610;
float[] beat = getBeatWindow();
int displaySize = showPrediction ? max(beat.length, beatWindowSize() * 2) : max(beat.length, beatWindowSize());
fill(218);
textAlign(LEFT, BASELINE);
textSize(14);
text(showPrediction ? "Aligned beat and fixed prediction" : "Statistical feature alignment", left, top - 19);
fill(125, 139, 158);
textSize(12);
String sourceLabel = filterChain.size() == 0 ? "raw (no filters)" : "pipeline output";
String detail = (showPrediction ? "2 × " : "1 × ") + beatWindowSize() + " observed samples • " + sourceLabel;
if (alignmentType > 0) detail += " • " + alignmentNames[alignmentType] + " aligned to sample " + alignmentOffset;
text(detail, left + 184, top - 19);
fill(25, 31, 41);
noStroke();
rect(left, top, right - left, bottom - top, 8);
if (showPrediction && particleFilterEnabled && alignmentType > 0 && beat.length >= beatWindowSize() * 2) {
updateParticleFilter(beat);
}
if (beat.length >= 2) {
float low = Float.MAX_VALUE;
float high = -Float.MAX_VALUE;
for (float value : beat) {
low = min(low, value);
high = max(high, value);
}
float padding = max((high - low) * 0.1, 1);
low -= padding;
high += padding;
stroke(55, 65, 79);
strokeWeight(1);
for (int i = 1; i < 4; i++) {
float y = lerp(top, bottom, i / 4.0);
line(left, y, right, y);
}
if (alignmentType > 0) {
float featureX = map(alignmentOffset, 0, displaySize - 1, left, right);
stroke(255, 190, 65, 190);
strokeWeight(1.5);
line(featureX, top, featureX, bottom);
int predictedIndex = alignmentOffset + fixedPeakInterval;
if (showPrediction && predictedIndex < displaySize) {
float predictedX = map(predictedIndex, 0, displaySize - 1, left, right);
float sigma = PREDICTION_SIGMA_SAMPLES;
noFill();
stroke(179, 137, 255);
strokeWeight(2.2);
beginShape();
for (int i = 0; i < displaySize; i++) {
float probability = exp(-0.5 * sq((i - predictedIndex) / sigma));
float x = map(i, 0, displaySize - 1, left, right);
float y = bottom - probability * (bottom - top) * 0.42;
vertex(x, y);
}
endShape();
stroke(179, 137, 255, 150);
strokeWeight(1);
line(predictedX, top, predictedX, bottom);
}
if (showPrediction && particleFilterEnabled) {
drawParticleEstimate(left, right, top, bottom, displaySize);
}
}
noFill();
stroke(65, 190, 245);
strokeWeight(2);
beginShape();
for (int i = 0; i < beat.length; i++) {
float x = map(i, 0, displaySize - 1, left, right);
float y = map(beat[i], low, high, bottom, top);
vertex(x, y);
}
endShape();
}
float buttonWidth = 106;
for (int i = 0; i < alignmentNames.length; i++) {
drawButton(left + i * (buttonWidth + 10), 628, buttonWidth, 27,
alignmentNames[i], alignmentType == i);
}
int maxOffset = max(1, beatWindowSize() - 1);
int minimumInterval = max(2, min(20, beatWindowSize()));
if (showPrediction) {
float predictedBPM = 60.0 * SAMPLE_RATE / max(fixedPeakInterval, 1);
drawSlider("Fixed peak interval", fixedPeakInterval, minimumInterval, beatWindowSize(), left, 677,
right - left, fixedPeakInterval + " samples • " + nf(predictedBPM, 0, 1) + " BPM");
}
drawSlider("Feature offset", alignmentOffset, 0, maxOffset, left, showPrediction ? 721 : 690,
right - left, alignmentOffset + " samples");
}
void initializeParticles() {
int minimumInterval = max(2, min(20, beatWindowSize()));
for (int i = 0; i < PARTICLE_COUNT; i++) {
particleIntervals[i] = constrain(
fixedPeakInterval + (float)randomGaussian() * PREDICTION_SIGMA_SAMPLES,
minimumInterval, beatWindowSize());
}
particleIntervalEstimate = fixedPeakInterval;
lastParticleDivision = -1;
}
void updateParticleFilter(float[] signal) {
int size = beatWindowSize();
long division = capturedSamples / size;
int config = 31 * size + alignmentType;
config = 31 * config + fixedPeakInterval;
for (FilterStage stage : filterChain) config = 31 * config + 7 * stage.type + stage.window;
if (config != lastParticleConfig) initializeParticles();
if (division == lastParticleDivision && config == lastParticleConfig) return;
float[] evidence = featureEvidence(signal, alignmentType - 1);
float[] weights = new float[PARTICLE_COUNT];
float totalWeight = 0;
int minimumInterval = max(2, min(20, size));
for (int i = 0; i < PARTICLE_COUNT; i++) {
particleIntervals[i] = constrain(
particleIntervals[i] + (float)randomGaussian() * 1.2,
minimumInterval, size);
int candidate = constrain(round(alignmentOffset + particleIntervals[i]), 0, evidence.length - 1);
weights[i] = evidence[candidate] + 0.000001;
totalWeight += weights[i];
}
particleIntervalEstimate = 0;
for (int i = 0; i < PARTICLE_COUNT; i++) {
weights[i] /= totalWeight;
particleIntervalEstimate += particleIntervals[i] * weights[i];
}
float[] resampled = new float[PARTICLE_COUNT];
float step = 1.0 / PARTICLE_COUNT;
float cursor = random(1) * step;
float cumulative = weights[0];
int source = 0;
for (int i = 0; i < PARTICLE_COUNT; i++) {
float target = cursor + i * step;
while (target > cumulative && source < PARTICLE_COUNT - 1) {
source++;
cumulative += weights[source];
}
resampled[i] = particleIntervals[source];
}
particleIntervals = resampled;
lastParticleDivision = division;
lastParticleConfig = config;
}
void drawParticleEstimate(float left, float right, float top, float bottom, int displaySize) {
stroke(255, 105, 105, 120);
strokeWeight(2);
for (int i = 0; i < PARTICLE_COUNT; i++) {
float position = alignmentOffset + particleIntervals[i];
float x = map(position, 0, displaySize - 1, left, right);
float y = top + 47 + (i % 5) * 3;
point(x, y);
}
float estimatePosition = alignmentOffset + particleIntervalEstimate;
float estimateX = map(estimatePosition, 0, displaySize - 1, left, right);
stroke(255, 105, 105);
strokeWeight(1.5);
line(estimateX, top, estimateX, bottom);
fill(255, 135, 135);
textSize(11);
textAlign(RIGHT, BASELINE);
float bpm = 60.0 * SAMPLE_RATE / max(particleIntervalEstimate, 1);
text("Particle estimate " + nf(particleIntervalEstimate, 0, 1) + " samples • " + nf(bpm, 0, 1) + " BPM",
right - 12, top + 54);
textAlign(LEFT, BASELINE);
}
void drawProbabilityRow(String label, float[] values, float left, float right,
float top, float rowHeight, color lineColor) {
float labelWidth = 72;
fill(111, 126, 145);
textSize(10);
textAlign(LEFT, CENTER);
text(label, left + 10, top + rowHeight / 2);
stroke(52, 62, 76);
line(left + labelWidth, top + rowHeight, right - 8, top + rowHeight);
noFill();
stroke(lineColor);
strokeWeight(1.5);
beginShape();
for (int i = 0; i < values.length; i++) {
float x = map(i, 0, max(values.length - 1, 1), left + labelWidth, right - 8);
float y = map(values[i], 0, maximum(values), top + rowHeight, top + 2);
vertex(x, y);
}
endShape();
textAlign(LEFT, BASELINE);
}
void updateBayesFilter() {
if (alignmentType == 0) return;
int size = beatWindowSize();
if (count < size) return;
int config = 31 * size + alignmentType;
config = 31 * config + round(timingTolerance);
for (FilterStage stage : filterChain) config = 31 * config + 7 * stage.type + stage.window;
long division = capturedSamples / size;
if (division == lastBayesDivision && config == lastBayesConfig && bayesPosterior.length == size) return;
boolean reset = config != lastBayesConfig || bayesPosterior.length != size;
if (reset) {
bayesPosterior = gaussianDistribution(size, constrain(alignmentOffset, 0, size - 1), timingTolerance);
}
float[] completedDivision = mostRecentCompleteDivision(size);
if (completedDivision.length != size) return;
bayesSignal = completedDivision;
bayesPrediction = blurDistribution(bayesPosterior, timingTolerance);
bayesEvidence = featureEvidence(bayesSignal, alignmentType - 1);
bayesPosterior = new float[size];
for (int i = 0; i < size; i++) bayesPosterior[i] = bayesPrediction[i] * bayesEvidence[i];
normalize(bayesPosterior);
lastBayesDivision = division;
lastBayesConfig = config;
}
float[] featureEvidence(float[] signal, int type) {
float[] evidence = new float[signal.length];
if (signal.length == 0) return evidence;
float low = signal[0];
float high = signal[0];
for (float value : signal) {
low = min(low, value);
high = max(high, value);
}
float range = max(high - low, 1);
float target = statistic(signal, 0, signal.length - 1, type);
for (int i = 0; i < signal.length; i++) {
float score;
if (type == 0) score = 1 - (signal[i] - low) / range;
else if (type == 1) score = (signal[i] - low) / range;
else score = 1 - min(abs(signal[i] - target) / range, 1);
evidence[i] = exp(4 * score);
}
normalize(evidence);
return evidence;
}
float[] gaussianDistribution(int size, int center, float sigma) {
float[] result = new float[size];
float safeSigma = max(sigma, 1);
for (int i = 0; i < size; i++) {
int distance = abs(i - center);
distance = min(distance, size - distance);
result[i] = exp(-0.5 * sq(distance / safeSigma));
}
normalize(result);
return result;
}
float[] blurDistribution(float[] input, float sigma) {
int size = input.length;
float[] result = new float[size];
int radius = min(size / 2, max(1, ceil(3 * sigma)));
float safeSigma = max(sigma, 1);
for (int i = 0; i < size; i++) {
for (int offset = -radius; offset <= radius; offset++) {
int source = (i - offset + size) % size;
float weight = exp(-0.5 * sq(offset / safeSigma));
result[i] += input[source] * weight;
}
}
normalize(result);
return result;
}
void normalize(float[] values) {
float total = 0;
for (float value : values) total += value;
if (total <= 0) {
for (int i = 0; i < values.length; i++) values[i] = 1.0 / max(values.length, 1);
return;
}
for (int i = 0; i < values.length; i++) values[i] /= total;
}
float maximum(float[] values) {
float result = 0;
for (float value : values) result = max(result, value);
return max(result, 0.000001);
}
int indexOfMaximum(float[] values) {
int best = 0;
for (int i = 1; i < values.length; i++) {
if (values[i] > values[best]) best = i;
}
return best;
}
float[] rotateSamples(float[] input, int start) {
float[] result = new float[input.length];
if (input.length == 0) return result;
int normalizedStart = ((start % input.length) + input.length) % input.length;
for (int i = 0; i < input.length; i++) result[i] = input[(normalizedStart + i) % input.length];
return result;
}
float[][] buildFilterStages() {
int visible = visibleCount();
if (!showFilters) return new float[0][visible];
float[][] outputs = new float[filterChain.size()][visible];
float[] input = new float[visible];
for (int i = 0; i < visible; i++) input[i] = sampleFromOldest(i);
for (int stage = 0; stage < filterChain.size(); stage++) {
FilterStage filter = filterChain.get(stage);
outputs[stage] = applyFilter(input, filter.type, filter.window);
input = outputs[stage];
}
return outputs;
}
float[] applyFilter(float[] input, int type, int window) {
float[] output = new float[input.length];
for (int endIndex = 0; endIndex < input.length; endIndex++) {
int length = min(window, endIndex + 1);
int start = endIndex - length + 1;
output[endIndex] = statistic(input, start, endIndex, type);
}
return output;
}
float statistic(float[] input, int start, int endIndex, int type) {
int length = endIndex - start + 1;
if (type == 0 || type == 1) {
float result = input[start];
for (int i = start + 1; i <= endIndex; i++) {
if (type == 0) result = min(result, input[i]);
else result = max(result, input[i]);
}
return result;
}
if (type == 2) {
float sum = 0;
for (int i = start; i <= endIndex; i++) sum += input[i];
return sum / length;
}
float[] values = new float[length];
for (int i = 0; i < length; i++) values[i] = input[start + i];
Arrays.sort(values);
if (type == 3) {
int middle = length / 2;
return length % 2 == 1 ? values[middle] : (values[middle - 1] + values[middle]) / 2.0;
}
// Mode uses rounded sensor units, avoiding float-equality surprises.
int bestValue = round(values[0]);
int bestCount = 1;
int runValue = bestValue;
int runCount = 1;
for (int i = 1; i < length; i++) {
int value = round(values[i]);
if (value == runValue) {
runCount++;
} else {
if (runCount > bestCount) {
bestCount = runCount;
bestValue = runValue;
}
runValue = value;
runCount = 1;
}
}
if (runCount > bestCount) bestValue = runValue;
return bestValue;
}
void drawHeader() {
fill(241, 244, 249);
textAlign(LEFT, BASELINE);
textSize(21);
text("Heart signal lab", 32, 32);
fill(133, 148, 168);
textSize(12);
text("Explore time windows and simple rolling filters", 32, 52);
float statusX = 480;
fill(serialMode ? color(90, 210, 150) : color(117, 184, 255));
noStroke();
circle(statusX, 37, 9);
fill(194, 204, 218);
textSize(13);
text(serialMode ? "ARDUINO" : "PYTHON", statusX + 12, 42);
text("IR " + nf(currentIR, 0, 0), statusX + 100, 42);
text(samplesPerSecond + " samples/s", statusX + 220, 42);
drawButton(32, 68, 122, 27, "FILTERS", showFilters);
drawButton(162, 68, 122, 27, "ALIGNMENT", showAlignment);
drawButton(292, 68, 122, 27, "PREDICTION", showPrediction);
drawButton(422, 68, 122, 27, "PARTICLES", particleFilterEnabled);
}
void drawControlPanel() {
float x = PANEL_LEFT;
float w = 330;
fill(25, 31, 41);
noStroke();
rect(x, 16, w, 728, 12);
fill(225, 230, 238);
textSize(16);
text("Controls", x + 20, 42);
drawButton(x + 20, 56, 138, 32, paused ? "Resume SPACE" : "Pause SPACE", paused);
drawButton(x + 172, 56, 138, 32, "Clear R", false);
fill(130, 145, 164);
textSize(11);
text("PORTS 0–9 select serial port", x + 20, 112);
drawSectionTitle("DISPLAY SCALE", x + 20, 150);
drawButton(x + 20, 160, 138, 32, "Auto A", autoScale);
drawButton(x + 172, 160, 138, 32, "Center C", false);
fill(151, 164, 182);
textSize(12);
text("observed", x + 20, 213);
fill(232);
textSize(14);
text(nf(signalLow, 0, 0) + " — " + nf(signalHigh, 0, 0), x + 20, 232);
if (!autoScale) {
fill(151, 164, 182);
textSize(11);
text("center " + nf(viewCenter, 0, 0) + " • range " + nf(viewRange, 0, 0), x + 135, 232);
}
drawButton(x + 20, 244, 65, 28, "Pan −", false);
drawButton(x + 93, 244, 65, 28, "Y range −", false);
drawButton(x + 166, 244, 65, 28, "Y range +", false);
drawButton(x + 239, 244, 71, 28, "Pan +", false);
drawSectionTitle("TIME WINDOW", x + 20, 302);
drawSlider("Display", windowSize, 10, BUFFER_SIZE, x + 20, 320, 290,
windowSize + " samples / " + nf(windowSize / float(SAMPLE_RATE), 0, 2) + " s");
fill(151, 164, 182);
textSize(12);
text("Equal divisions", x + 20, 368);
drawButton(x + 20, 376, 44, 28, "−", false);
fill(232);
textAlign(CENTER, CENTER);
textSize(15);
text(divisions, x + 165, 390);
textAlign(LEFT, BASELINE);
drawButton(x + 266, 376, 44, 28, "+", false);
if (showFilters) {
drawSectionTitle("ADD FILTER", x + 20, 432);
for (int i = 0; i < filterNames.length; i++) {
int column = i % 2;
int row = i / 2;
boolean added = indexOfFilter(i) >= 0;
String label = (i + 1) + " " + (added ? "✓ " : "+ ") + filterNames[i];
drawButton(x + 20 + column * 148, 442 + row * 35, 140, 29, label, added);
}
drawSectionTitle("PIPELINE • TOP RUNS FIRST", x + 20, 556);
if (filterChain.size() == 0) {
fill(133, 148, 168);
textSize(12);
text("Add filters above to build a stack.", x + 20, 585);
}
for (int i = 0; i < filterChain.size(); i++) drawPipelineRow(i, x + 20, 568 + i * 31, 290, 27);
}
}
void drawPipelineRow(int index, float x, float y, float w, float h) {
FilterStage stage = filterChain.get(index);
boolean selected = index == selectedStage;
noStroke();
fill(selected ? color(47, 59, 75) : color(34, 42, 54));
rect(x, y, w, h, 6);
fill(filterColors[stage.type]);
rect(x, y, 5, h, 6, 0, 0, 6);
fill(218, 225, 234);
textAlign(LEFT, CENTER);
textSize(12);
text((index + 1) + " " + filterNames[stage.type], x + 14, y + h / 2);
fill(139, 153, 171);
drawTinyButton(x + 126, y + 4, 20, h - 8, "−", stage.window > 1);
textAlign(CENTER, CENTER);
text(stage.window, x + 166, y + h / 2);
drawTinyButton(x + 185, y + 4, 20, h - 8, "+", stage.window < windowSize);
drawTinyButton(x + 213, y + 4, 20, h - 8, "↑", index > 0);
drawTinyButton(x + 237, y + 4, 20, h - 8, "↓", index < filterChain.size() - 1);
drawTinyButton(x + 266, y + 4, 20, h - 8, "×", true);
textAlign(LEFT, BASELINE);
}
void drawTinyButton(float x, float y, float w, float h, String label, boolean enabled) {
noStroke();
fill(enabled ? color(54, 65, 80) : color(39, 47, 59));
rect(x, y, w, h, 4);
fill(enabled ? color(205, 214, 226) : color(89, 101, 116));
textAlign(CENTER, CENTER);
textSize(12);
text(label, x + w / 2, y + h / 2 - 1);
}
void drawSectionTitle(String label, float x, float y) {
fill(107, 124, 146);
textSize(11);
text(label, x, y);
}
void drawButton(float x, float y, float w, float h, String label, boolean active) {
boolean hover = pointIn(mouseX, mouseY, x, y, w, h);
noStroke();
if (active) fill(42, 119, 168);
else if (hover) fill(52, 62, 77);
else fill(38, 46, 59);
rect(x, y, w, h, 7);
fill(active ? color(246) : color(199, 209, 222));
textAlign(CENTER, CENTER);
textSize(12);
text(label, x + w / 2, y + h / 2 - 1);
textAlign(LEFT, BASELINE);
}
void drawSlider(String label, float value, float minimum, float maximum,
float x, float y, float w, String valueLabel) {
fill(151, 164, 182);
textSize(12);
text(label, x, y);
textAlign(RIGHT, BASELINE);
fill(215, 222, 232);
text(valueLabel, x + w, y);
textAlign(LEFT, BASELINE);
float trackY = y + 20;
stroke(58, 68, 83);
strokeWeight(5);
line(x, trackY, x + w, trackY);
float knobX = map(value, minimum, maximum, x, x + w);
stroke(67, 174, 232);
line(x, trackY, knobX, trackY);
noStroke();
fill(229, 238, 247);
circle(knobX, trackY, 14);
}
boolean pointIn(float px, float py, float x, float y, float w, float h) {
return px >= x && px <= x + w && py >= y && py <= y + h;
}
void keyPressed() {
if (key == 'a' || key == 'A') toggleAutoScale();
if (key == 'c' || key == 'C') centerView();
if (key == ' ') paused = !paused;
if (key == 'r' || key == 'R') clearSamples();
if (key == 'm' || key == 'M') toggleSource();
if (key == '-' || key == '_') windowSize -= 10;
if (key == '=' || key == '+') windowSize += 10;
if ((key == '[' || key == '{') && selectedStage >= 0)
filterChain.get(selectedStage).window -= keyEvent.isShiftDown() ? 10 : 1;
if ((key == ']' || key == '}') && selectedStage >= 0)
filterChain.get(selectedStage).window += keyEvent.isShiftDown() ? 10 : 1;
if (key == 'z' || key == 'Z') changeViewRange(1 / 1.35);
if (key == 'x' || key == 'X') changeViewRange(1.35);
if (key >= '0' && key <= '9') selectSerialPort(key - '0');
if (key == CODED) {
if (keyEvent.isShiftDown() && keyCode == UP) moveSelectedStage(-1);
else if (keyEvent.isShiftDown() && keyCode == DOWN) moveSelectedStage(1);
else if (keyCode == UP) {
autoScale = false;
viewCenter += viewRange * 0.1;
}
else if (keyCode == DOWN) {
autoScale = false;
viewCenter -= viewRange * 0.1;
}
}
clampControls();
}
void mousePressed() {
float x = PANEL_LEFT;
if (pointIn(mouseX, mouseY, 32, 68, 122, 27)) { toggleLectureStage(1); return; }
if (pointIn(mouseX, mouseY, 162, 68, 122, 27)) { toggleLectureStage(2); return; }
if (pointIn(mouseX, mouseY, 292, 68, 122, 27)) { toggleLectureStage(3); return; }
if (pointIn(mouseX, mouseY, 422, 68, 122, 27)) { toggleLectureStage(4); return; }
if (showAlignment) {
for (int i = 0; i < alignmentNames.length; i++) {
if (pointIn(mouseX, mouseY, GRAPH_LEFT + i * 116, 628, 106, 27)) {
alignmentType = i;
return;
}
}
if (showPrediction && pointIn(mouseX, mouseY, GRAPH_LEFT, 686, GRAPH_RIGHT - GRAPH_LEFT, 28)) {
draggingTolerance = true;
setToleranceFromMouse();
return;
}
float offsetClickY = showPrediction ? 730 : 699;
if (pointIn(mouseX, mouseY, GRAPH_LEFT, offsetClickY, GRAPH_RIGHT - GRAPH_LEFT, 28)) {
draggingAlignment = true;
setAlignmentFromMouse();
return;
}
}
if (pointIn(mouseX, mouseY, x + 20, 56, 138, 32)) paused = !paused;
else if (pointIn(mouseX, mouseY, x + 172, 56, 138, 32)) clearSamples();
else if (pointIn(mouseX, mouseY, x + 20, 160, 138, 32)) toggleAutoScale();
else if (pointIn(mouseX, mouseY, x + 172, 160, 138, 32)) centerView();
else if (pointIn(mouseX, mouseY, x + 20, 244, 65, 28)) panView(-1);
else if (pointIn(mouseX, mouseY, x + 93, 244, 65, 28)) changeViewRange(1 / 1.35);
else if (pointIn(mouseX, mouseY, x + 166, 244, 65, 28)) changeViewRange(1.35);
else if (pointIn(mouseX, mouseY, x + 239, 244, 71, 28)) panView(1);
else if (pointIn(mouseX, mouseY, x + 20, 376, 44, 28)) divisions--;
else if (pointIn(mouseX, mouseY, x + 266, 376, 44, 28)) divisions++;
else if (pointIn(mouseX, mouseY, x + 20, 329, 290, 28)) {
draggingWindow = true;
setWindowFromMouse();
}
else {
boolean handled = false;
if (showFilters) {
for (int i = 0; i < filterNames.length; i++) {
int column = i % 2;
int row = i / 2;
if (pointIn(mouseX, mouseY, x + 20 + column * 148, 442 + row * 35, 140, 29)) {
addOrSelectFilter(i);
handled = true;
}
}
if (!handled) handlePipelineClick(x + 20, 568);
}
}
clampControls();
}
void toggleLectureStage(int stage) {
if (stage == 1) {
showFilters = !showFilters;
if (!showFilters) {
showAlignment = false;
showPrediction = false;
particleFilterEnabled = false;
}
} else if (stage == 2) {
if (showAlignment) {
showAlignment = false;
showPrediction = false;
particleFilterEnabled = false;
} else {
showFilters = true;
showAlignment = true;
}
} else if (stage == 3) {
if (showPrediction) {
showPrediction = false;
particleFilterEnabled = false;
} else {
showFilters = true;
showAlignment = true;
showPrediction = true;
}
} else if (stage == 4) {
if (particleFilterEnabled) {
particleFilterEnabled = false;
} else {
showFilters = true;
showAlignment = true;
showPrediction = true;
particleFilterEnabled = true;
initializeParticles();
}
}
}
void mouseDragged() {
if (draggingWindow) setWindowFromMouse();
if (draggingAlignment) setAlignmentFromMouse();
if (draggingTolerance) setToleranceFromMouse();
}
void mouseReleased() {
draggingWindow = false;
draggingFilter = false;
draggingAlignment = false;
draggingTolerance = false;
}
void setWindowFromMouse() {
float fraction = constrain((mouseX - (PANEL_LEFT + 20)) / 290.0, 0, 1);
windowSize = round(lerp(10, BUFFER_SIZE, fraction) / 10.0) * 10;
clampControls();
}
void setFilterFromMouse() {
if (selectedStage < 0 || selectedStage >= filterChain.size()) return;
float fraction = constrain((mouseX - (PANEL_LEFT + 20)) / 290.0, 0, 1);
filterChain.get(selectedStage).window = round(lerp(1, windowSize, fraction));
clampControls();
}
void setAlignmentFromMouse() {
float fraction = constrain((mouseX - GRAPH_LEFT) / (GRAPH_RIGHT - GRAPH_LEFT), 0, 1);
alignmentOffset = round(lerp(0, max(1, beatWindowSize() - 1), fraction));
}
void setToleranceFromMouse() {
float fraction = constrain((mouseX - GRAPH_LEFT) / (GRAPH_RIGHT - GRAPH_LEFT), 0, 1);
int minimumInterval = max(2, min(20, beatWindowSize()));
fixedPeakInterval = round(lerp(minimumInterval, beatWindowSize(), fraction));
}
int indexOfFilter(int type) {
for (int i = 0; i < filterChain.size(); i++) {
if (filterChain.get(i).type == type) return i;
}
return -1;
}
void addOrSelectFilter(int type) {
int existing = indexOfFilter(type);
if (existing >= 0) {
selectedStage = existing;
} else {
filterChain.add(new FilterStage(type, min(10, windowSize)));
selectedStage = filterChain.size() - 1;
}
}
void handlePipelineClick(float x, float firstY) {
for (int i = 0; i < filterChain.size(); i++) {
float y = firstY + i * 31;
if (!pointIn(mouseX, mouseY, x, y, 290, 27)) continue;
selectedStage = i;
if (mouseX >= x + 266) removeSelectedStage();
else if (mouseX >= x + 237) moveSelectedStage(1);
else if (mouseX >= x + 213) moveSelectedStage(-1);
else if (mouseX >= x + 185 && mouseX <= x + 205) adjustSelectedWindow(1);
else if (mouseX >= x + 126 && mouseX <= x + 146) adjustSelectedWindow(-1);
return;
}
}
void adjustSelectedWindow(int direction) {
if (selectedStage < 0 || selectedStage >= filterChain.size()) return;
int step = mouseEvent != null && mouseEvent.isShiftDown() ? 10 : 1;
filterChain.get(selectedStage).window += direction * step;
clampControls();
}
void moveSelectedStage(int direction) {
if (selectedStage < 0 || selectedStage >= filterChain.size()) return;
int target = constrain(selectedStage + direction, 0, filterChain.size() - 1);
if (target == selectedStage) return;
FilterStage moving = filterChain.remove(selectedStage);
filterChain.add(target, moving);
selectedStage = target;
}
void removeSelectedStage() {
if (selectedStage < 0 || selectedStage >= filterChain.size()) return;
filterChain.remove(selectedStage);
if (filterChain.size() == 0) selectedStage = -1;
else selectedStage = min(selectedStage, filterChain.size() - 1);
}
void toggleAutoScale() {
if (autoScale && visibleCount() > 1) {
viewCenter = (autoLow + autoHigh) / 2;
viewRange = max(autoHigh - autoLow, 10);
}
autoScale = !autoScale;
}
void centerView() {
viewCenter = currentIR;
viewInitialized = true;
autoScale = false;
}
void panView(float direction) {
autoScale = false;
viewCenter += direction * viewRange * 0.1;
}
void changeViewRange(float factor) {
autoScale = false;
viewRange *= factor;
clampControls();
}
void clearSamples() {
count = 0;
head = 0;
capturedSamples = 0;
bayesPrediction = new float[0];
bayesEvidence = new float[0];
bayesPosterior = new float[0];
bayesSignal = new float[0];
lastBayesDivision = -1;
lastParticleDivision = -1;
}
void toggleSource() {
if (serialMode) useSimulator("Python simulator on UDP 8765");
else connectSerialOrUseSimulator();
}
void selectSerialPort(int index) {
String[] ports = Serial.list();
if (index < 0 || index >= ports.length) {
println("No serial port at index " + index);
printArray(ports);
return;
}
if (arduino != null) {
arduino.stop();
arduino = null;
}
try {
arduino = new Serial(this, ports[index], 115200);
arduino.clear();
serialMode = true;
sourceName = ports[index];
println("Using serial port " + index + ": " + ports[index]);
}
catch (RuntimeException error) {
println("Could not open serial port " + index + ": " + error.getMessage());
useSimulator("Python simulator on UDP 8765");
}
}
void clampControls() {
windowSize = constrain(windowSize, 10, BUFFER_SIZE);
divisions = constrain(divisions, 1, 10);
for (FilterStage stage : filterChain) stage.window = constrain(stage.window, 1, windowSize);
alignmentOffset = constrain(alignmentOffset, 0, max(1, beatWindowSize() - 1));
timingTolerance = constrain(timingTolerance, 1, max(2, beatWindowSize() / 2));
fixedPeakInterval = constrain(fixedPeakInterval, max(2, min(20, beatWindowSize())), beatWindowSize());
viewRange = constrain(viewRange, 10, 262143);
}
Use the 0-9 Keys to find your Arduino Port and Heart Rate Signal
Use the 0-9 keys to select the port that your Arduino is attached to.
Find the Scale and Offset for your Heart Beat
Put your finger on the sensor. Using the controls on the screen (or keyboard shortcuts), get the signal roughly into the right range. You should be able to visually see a reasonably good heart rate graph show up. If you can't see peaks very easily, you might be plugged into the circuit wrong, or you might be touching the sensor incorrectly.
Pre-filter the Signal
Using the filters as directed, find the right set of filters that make the signal more clear. You want something that gets rid of noise, but doesn't get read of features of the signal you are interested in, like peaks. Use as many filters as is helpful.
Identify the Signal Start and End
How might you go about designing a way to find a signal start and end? Discuss an algorithm with your group.
Wait for Further Instruction
There's more! But we need to have a chat about particle filters first.