Fab Academy 2026

Week 15: System Integration

Putting the PCB, the app, the enclosure and the code of Ancora together in one wearable.

Software

KiCad, MIT App Inventor, SolidWorks and Arduino IDE

Machines

Prusa MK4S and xTool F1 Ultra v2

Main Skills

PCB redesign, app development, enclosure design and firmware

Assignments

Individual Assignment

Workflow Overview

1. PCB Redesign

Change the layout so the sensor touches the skin and the ESP32-C3 sits on the other side.

2. Mobile App

Build the app that controls the output type and the exercise mode.

3. Enclosure

Design, print and close the case that protects the PCB.

4. Programming

Join the sensor code, the Bluetooth code and the breathing exercise.

PCB Redesign

First, I used the PCB from my Output Devices week and changed the layout.

I placed the sensor on one side so it touches the skin. The ESP32-C3 goes on the other side, so it does not bother the user when the bracelet is on the wrist.

I also adapted the size of the board to match a 3.7 V LiPo battery. This way, the battery and the PCB can be stacked in a small space.

Sensor Side

The MAX30102 faces the skin.

ESP Side

The ESP32-C3 stays on the outside.

Board Size

Same size as the 3.7 V LiPo battery.

Battery Connection

I connected the LiPo battery to the BAT pads of the ESP32-C3. I saw that when the battery is connected directly to these pads, it also charges when I plug in the USB-C cable.

Since the bracelet needs to be charged without opening the case, this was the simplest option.

LiPo battery soldered to the BAT pads of the ESP32-C3
Battery connected to the BAT pads.

Mobile App

Once the PCB was assembled, I designed an app in MIT App Inventor. The app connects to the ESP32-C3 and lets the user choose the output: LED or vibration.

The app also has an exercise mode. When I turn it on, the bracelet does not activate the output when my pulse goes up.

I based the app on my Interface and Application Programming week.

App Background

I asked Gemini to generate the background of the app. I asked for blue, since color psychology says it helps to calm.

I also asked for an anchor in the middle, because "Ancora" means anchor in Spanish.

Final screen of the Ancora app with the blue background and the anchor
Final design of the Ancora app.

Output Selection

The user chooses LED or vibration.

Exercise Mode

A switch tells the bracelet to ignore the pulse increase.

Saved Settings

The ESP32-C3 remembers the output, even if the app closes.

Saving the Settings

I programmed the app so the ESP32-C3 stores the output type the user chose. This way, if the app closes, the bracelet still gives only the output that the user asked for.

I also made the app read the state of the switch when it connects again. Then the switch shows as on or off, depending on what the user left before.

MIT App Inventor blocks of the Ancora app
App Inventor blocks.

Testing the App

To test the app, I checked three things.

1. Output Works

The LED and the motor turn on from the app.

2. Output Off

When I turn them off in the app, they stop working.

3. Exercise Mode

With the switch on, the outputs stay off. With the switch off, the selected output works again.

Here is the code that I used to test the app:

#include <BLE.h>
#include <Preferences.h>
#include <math.h>


// BLE ids, the app uses the same ones to find the bracelet
static const BLEUUID SERVICE_UUID("4fafc201-1fb5-459e-8fcc-c5c9c331914b");
static const BLEUUID CHAR_UUID("beb5483e-36e1-4688-b7f5-ea07361b26a8");


const int LED_PIN = D1;
const int MOTOR_PIN = D2;


const int PWM_FREQ = 5000;
const int PWM_BITS = 8;


const int LED_MAX = 120;
const int MOTOR_MIN = 60;
const int MOTOR_MAX = 140;


// how long one full "breath" lasts 
const float LED_PERIOD_MS = 3000.0;
const float MOTOR_PERIOD_MS = 2500.0;


Preferences prefs;


// state[0] = exercise mode, state[1] = LED, state[2] = vibration
volatile uint8_t state[3] = {0, 0, 0};


// flags so the callbacks don't print directly
volatile bool newData = false;
volatile bool connectionEvent = false;
volatile bool isConnected = false;


// smooth wave from 0 to 1 and back, used for the breathing effect
float wave(float period) {
  float phase = (millis() % (unsigned long)period) / period;
  return 0.5 - 0.5 * cosf(2.0 * PI * phase);
}


// prints what the bracelet has on/off right now
void printState() {
  Serial.printf("State -> Exercise:%d LED:%d Vibration:%d\n",
                state[0], state[1], state[2]);
}


// quick test at boot to check LED and motor work
void startupTest() {
  Serial.println("Startup test: LED and motor for 1 second...");
  ledcWrite(LED_PIN, LED_MAX);
  ledcWrite(MOTOR_PIN, MOTOR_MAX);
  delay(1000);
  ledcWrite(LED_PIN, 0);
  ledcWrite(MOTOR_PIN, 0);
}


void setup() {
  Serial.begin(115200);
  delay(2000);
  Serial.println("Starting Ancora...");


  // set up PWM and start with everything off
  ledcAttach(LED_PIN, PWM_FREQ, PWM_BITS);
  ledcAttach(MOTOR_PIN, PWM_FREQ, PWM_BITS);
  ledcWrite(LED_PIN, 0);
  ledcWrite(MOTOR_PIN, 0);


  startupTest();


  // load the last saved settings from memory
  uint8_t savedState[3] = {0, 0, 0};
  prefs.begin("ancora", false);
  if (prefs.getBytesLength("state") == 3) {
    prefs.getBytes("state", savedState, 3);
  }
  for (int i = 0; i < 3; i++) state[i] = savedState[i];


  Serial.print("Saved state loaded. ");
  printState();


  // start bluetooth
  BTStatus status = BLE.begin("XIAO-C3");
  if (!status) {
    Serial.printf("BLE failed: %s\n", status.toString());
    return;
  }


  BLEServer server = BLE.createServer();


  // just flag the events, loop() prints them
  server.onConnect([](BLEServer &s, const BLEConnInfo &info) {
    isConnected = true;
    connectionEvent = true;
  });
  server.onDisconnect([](BLEServer &s, const BLEConnInfo &info, uint8_t reason) {
    isConnected = false;
    connectionEvent = true;
  });
  server.advertiseOnDisconnect(true);  // so the app can reconnect


  BLEService service = server.createService(SERVICE_UUID);
  BLECharacteristic characteristic = service.createCharacteristic(
      CHAR_UUID,
      BLEProperty::Read | BLEProperty::Write,
      BLEPermission::ReadWriteOpen);
  characteristic.setValue(savedState, 3);


  // runs when the app sends new settings
  characteristic.onWrite([](BLECharacteristic &c, const BLEConnInfo &info) {
    size_t len = 0;
    const uint8_t *data = c.getValue(&len);


    if (data != nullptr && len >= 3) {
      uint8_t newState[3];
      for (int i = 0; i < 3; i++) {
        newState[i] = data[i] ? 1 : 0;  // anything above 0 counts as ON
        state[i] = newState[i];
      }
      prefs.putBytes("state", newState, 3);  // save it for next time
      c.setValue(newState, 3);
      newData = true;
    }
  });


  server.start();
  BLE.getAdvertising().addServiceUUID(SERVICE_UUID);
  BLE.startAdvertising();


  Serial.print("BLE ready. Address: ");
  Serial.println(BLE.getAddress().toString());
  Serial.println("Waiting for the app to connect...");
}


void loop() {
  // tell me when the app connects or disconnects
  if (connectionEvent) {
    connectionEvent = false;
    Serial.println(isConnected ? ">>> APP CONNECTED via BLE" : ">>> APP DISCONNECTED");
  }


  // tell me when new settings arrive
  if (newData) {
    newData = false;
    Serial.print("Data received. ");
    printState();
  }


  // exercise mode turns off the alerts so there are no false alarms
  bool exerciseMode = state[0];
  bool ledOn = state[1] && !exerciseMode;
  bool motorOn = state[2] && !exerciseMode;


  // LED fades in and out following the breathing wave
  ledcWrite(LED_PIN, ledOn ? (int)(wave(LED_PERIOD_MS) * LED_MAX) : 0);


  // motor does the same but never goes below MOTOR_MIN so it keeps moving
  if (motorOn) {
    ledcWrite(MOTOR_PIN, MOTOR_MIN + (int)(wave(MOTOR_PERIOD_MS) * (MOTOR_MAX - MOTOR_MIN)));
  } else {
    ledcWrite(MOTOR_PIN, 0);
  }


  delay(10);
}

Enclosure Design

With the PCB and the app ready, I designed a case to cover the PCB. First, I measured the board with a caliper.

My first version was only a box with the dimensions of the PCB. Then I added the rest, step by step.

1. Basic Box

A box with the PCB measurements.

2. LED Window

An opening so the LED can be seen.

3. USB-C Opening

A space for the cable that charges the battery.

4. Strap Tabs

Tabs to hold the straps.

In SolidWorks, I used a tolerance of 0.2 mm so the PCB fits in the case.

3D Printing

I printed the case on a Prusa MK4S. I used generic blue PETG.

3D printed blue PETG case of the Ancora bracelet
3D printed case.

Lid and Engraving

Finally, I designed a small lid. I will glue it with super glue, so I can peel it off and open the case if I need to repair the circuit.

I engraved an anchor on the lid with the xTool F1 Ultra v2.

Programming

For the sensor, I used the code from my Output Devices week as a base.

To connect the ESP32 with the app, I used the code from my Interface week.

This week, I changed the outputs. Before, the LED and the motor only turned on. Now they guide the user through a breathing exercise to help get out of an anxiety attack.

Pulse Detection (from Week 10)

I did not change the pulse detection this week. I used the one I made in Week 10, which already filters the beats and compares them with a resting baseline.

Noise Filter

Only readings between 40 and 140 BPM are saved.

Average

The code averages the last 12 readings.

Resting Baseline

The first 20 readings set the base pulse.

Strong Beats

The alert starts after 3 beats in a row, 4 BPM or more above the base.

Guided Breathing

The exercise has three steps: inhale for 4 seconds, hold for 7 seconds and exhale for 8 seconds.

1. Inhale

The LED gets brighter and the vibration pulses get closer.

2. Hold

The LED and the motor stays on.

3. Exhale

The LED fades out and the vibration pulses get slower.

#include <BLE.h>
#include <Preferences.h>
#include <Wire.h>
#include <math.h>
#include "MAX30105.h"
#include "heartRate.h"

static const BLEUUID SERVICE_UUID("4fafc201-1fb5-459e-8fcc-c5c9c331914b");
static const BLEUUID CHAR_UUID("beb5483e-36e1-4688-b7f5-ea07361b26a8");

const int LED_PIN = D1;
const int MOTOR_PIN = D2;
const int PWM_FREQ = 5000;
const int PWM_BITS = 8;

const int LED_MAX = 120;
const int MOTOR_MIN = 60;
const int MOTOR_MAX = 140;

const unsigned long INHALE_MS = 4000;
const unsigned long HOLD_MS = 7000;
const unsigned long EXHALE_MS = 8000;
const unsigned long CYCLE_MS = INHALE_MS + HOLD_MS + EXHALE_MS;

MAX30105 particleSensor;

// keeps the last 12 readings to get an average
const byte RATE_SIZE = 12;
byte rates[RATE_SIZE];
byte rateSpot = 0;
long lastBeat = 0;
float beatsPerMinute;
int beatAvg = 0;

// calibration: first 20 beats to find my resting pulse
bool baselineSet = false;
int calibrationCount = 0;
const int TOTAL_CAL_SAMPLES = 20;
float calibrationSum = 0;
float baselinePulse = 0;

// alert logic: pulse needs to stay high for a few beats in a row
int highBeatsInARow = 0;
const int MIN_HIGH_BEATS = 3;
const float DIFF_THRESHOLD = 4.0;
bool alertActive = false;

bool sessionActive = false;
unsigned long sessionStart = 0;
const unsigned long MIN_SESSION_MS = 60000;  // guide lasts at least 1 min

Preferences prefs;
volatile uint8_t state[3] = {0, 0, 0};  // [Exercise, LED, Vibration]
volatile bool newData = false;
volatile bool connectionEvent = false;
volatile bool isConnected = false;


// prints what the bracelet has on/off right now
void printState() {
  Serial.printf("State -> Exercise:%d  LED:%d  Vibration:%d\n",
                state[0], state[1], state[2]);
}

// turns LED and motor off
void turnOffOutputs() {
  ledcWrite(LED_PIN, 0);
  ledcWrite(MOTOR_PIN, 0);
}

// quick test at boot to check LED and motor work
void startupTest() {
  Serial.println("Startup test: LED and motor for 1 second...");
  ledcWrite(LED_PIN, LED_MAX);
  ledcWrite(MOTOR_PIN, MOTOR_MAX);
  delay(1000);
  turnOffOutputs();
}

// physical alert: 2 short pulses when it connects, 1 long one when it disconnects so the user knows what happened without the serial monitor
void connectionAlert(bool connected) {
  int pulses = connected ? 2 : 1;
  int duration = connected ? 150 : 600;

  for (int i = 0; i < pulses; i++) {
    ledcWrite(LED_PIN, LED_MAX);
    ledcWrite(MOTOR_PIN, MOTOR_MAX);
    delay(duration);
    turnOffOutputs();
    if (i < pulses - 1) delay(150);
  }
}

// same alert but in the serial monitor just for the testing phase
void serialAlert(bool connected) {
  Serial.println();
  Serial.println("==============================");
  if (connected) {
    Serial.println("  APP CONNECTED via BLE");
    Serial.printf("  Uptime: %lu s\n", millis() / 1000);
    Serial.print("  ");
    printState();
  } else {
    Serial.println("  APP DISCONNECTED");
    Serial.printf("  Uptime: %lu s\n", millis() / 1000);
    Serial.println("  Advertising again, waiting for connection...");
  }
  Serial.println("==============================");
  Serial.println();
}

// gives a value from 0.0 to 1.0 depending on where we are in the 4-7-8 cycle
float breathingIntensity() {
  unsigned long t = (millis() - sessionStart) % CYCLE_MS;

  if (t < INHALE_MS) {
    // inhale: goes up
    return (float)t / INHALE_MS;
  } else if (t < INHALE_MS + HOLD_MS) {
    // hold: stays at max
    return 1.0;
  } else {
    // exhale: goes down
    return 1.0 - (float)(t - INHALE_MS - HOLD_MS) / EXHALE_MS;
  }
}

void startBLE(const uint8_t *savedState) {
  BTStatus status = BLE.begin("Ancora");
  if (!status) {
    Serial.printf("BLE failed: %s\n", status.toString());
    return;
  }

  BLEServer server = BLE.createServer();

  // just flag the events, loop() handles them
  server.onConnect([](BLEServer &s, const BLEConnInfo &conn) {
    isConnected = true;
    connectionEvent = true;
  });

  server.onDisconnect([](BLEServer &s, const BLEConnInfo &conn, uint8_t reason) {
    isConnected = false;
    connectionEvent = true;
  });

  server.advertiseOnDisconnect(true);  // so the app can reconnect

  BLEService service = server.createService(SERVICE_UUID);
  BLECharacteristic characteristic = service.createCharacteristic(
      CHAR_UUID,
      BLEProperty::Read | BLEProperty::Write,
      BLEPermission::ReadWriteOpen);

  characteristic.setValue(savedState, 3);

  characteristic.onWrite([](BLECharacteristic &c, const BLEConnInfo &conn) {
    size_t len = 0;
    const uint8_t *data = c.getValue(&len);

    if (data != nullptr && len >= 3) {
      uint8_t newState[3];
      for (int i = 0; i < 3; i++) {
        newState[i] = data[i] ? 1 : 0;  // anything above 0 counts as ON
        state[i] = newState[i];
      }
      prefs.putBytes("state", newState, 3);  // save it for next time
      c.setValue(newState, 3);
      newData = true;
    }
  });

  server.start();
  BLE.getAdvertising().addServiceUUID(SERVICE_UUID);
  BLE.startAdvertising();

  Serial.print("BLE ready. Address: ");
  Serial.println(BLE.getAddress().toString());
}

// back to normal, reset the alert stuff
void resetDetection() {
  highBeatsInARow = 0;
  alertActive = false;
}

void readSensor() {
  long irValue = particleSensor.getIR();

  //bracelet not on the wrist
  if (irValue < 50000) {
    resetDetection();
    return;
  }

  // only keep going when the sensor detects a heartbeat
  if (!checkForBeat(irValue)) return;

  long delta = millis() - lastBeat;
  lastBeat = millis();
  beatsPerMinute = 60 / (delta / 1000.0);

  // ignore weird values (too slow or too fast)
  if (beatsPerMinute >= 140 || beatsPerMinute <= 40) return;

  // save the reading and get the average
  rates[rateSpot++] = (byte)beatsPerMinute;
  rateSpot %= RATE_SIZE;

  int sum = 0;
  for (byte x = 0; x < RATE_SIZE; x++) sum += rates[x];
  beatAvg = sum / RATE_SIZE;

  // still calibrating, collecting beats for the baseline
  if (!baselineSet) {
    calibrationSum += beatsPerMinute;
    calibrationCount++;
    if (calibrationCount >= TOTAL_CAL_SAMPLES) {
      baselinePulse = calibrationSum / TOTAL_CAL_SAMPLES;
      baselineSet = true;
      Serial.printf("Baseline pulse: %.1f BPM\n", baselinePulse);
    }
    return;
  }

  // exercise mode: no alerts, so no false alarms
  if (state[0]) {
    resetDetection();
    return;
  }

  // how far am I from my normal pulse
  float difference = beatAvg - baselinePulse;
  if (difference >= DIFF_THRESHOLD) {
    highBeatsInARow++;
    if (highBeatsInARow >= MIN_HIGH_BEATS) alertActive = true;
  } else {
    resetDetection();
  }

  Serial.printf("BPM:%.0f  Avg:%d  Base:%.0f  Alert:%d\n",
                beatsPerMinute, beatAvg, baselinePulse, alertActive);
}

void updateSession() {
  bool exerciseMode = state[0];

  // exercise mode cancels any session
  if (exerciseMode) {
    sessionActive = false;
    return;
  }

  // alert just started, so start the guide
  if (!sessionActive && alertActive) {
    sessionActive = true;
    sessionStart = millis();
    Serial.println(">>> Starting 4-7-8 breathing guide");
  }

  // stop only if the alert is gone AND the minimum time already passed
  if (sessionActive && !alertActive &&
      millis() - sessionStart >= MIN_SESSION_MS) {
    sessionActive = false;
    Serial.println(">>> Breathing guide finished");
  }
}

void updateOutputs() {
  // only use what I picked in the app (LED, vibration or both)
  bool ledOn = sessionActive && state[1];
  bool motorOn = sessionActive && state[2];

  float intensity = sessionActive ? breathingIntensity() : 0.0;

  ledcWrite(LED_PIN, ledOn ? (int)(intensity * LED_MAX) : 0);

  // motor never goes below MOTOR_MIN so it keeps moving
  if (motorOn) {
    ledcWrite(MOTOR_PIN, MOTOR_MIN + (int)(intensity * (MOTOR_MAX - MOTOR_MIN)));
  } else {
    ledcWrite(MOTOR_PIN, 0);
  }
}

void setup() {
  Serial.begin(115200);
  delay(2000);
  Serial.println("Starting Ancora...");

  // set up PWM and start with everything off
  ledcAttach(LED_PIN, PWM_FREQ, PWM_BITS);
  ledcAttach(MOTOR_PIN, PWM_FREQ, PWM_BITS);
  turnOffOutputs();
  startupTest();

  // if the sensor isn't found, stop here
  Wire.begin(22, 23);
  if (!particleSensor.begin(Wire, I2C_SPEED_FAST)) {
    Serial.println("MAX30102 not found");
    while (1);
  }
  particleSensor.setup(60, 1, 2, 200, 411, 4096);

  // load the last saved settings from memory
  uint8_t savedState[3] = {0, 0, 0};
  prefs.begin("ancora", false);
  if (prefs.getBytesLength("state") == 3) {
    prefs.getBytes("state", savedState, 3);
  }
  for (int i = 0; i < 3; i++) state[i] = savedState[i];
  Serial.print("Saved state loaded. ");
  printState();

  startBLE(savedState);
  Serial.println("Waiting for the app to connect...");
}

void loop() {
  // tell me when the app connects or disconnects
  if (connectionEvent) {
    connectionEvent = false;
    serialAlert(isConnected);
    connectionAlert(isConnected);
  }

  // tell me when new settings arrive
  if (newData) {
    newData = false;
    Serial.print("Data received. ");
    printState();
  }

  readSensor();
  updateSession();
  updateOutputs();
}

Debugging and Problems

Sharp Corners

The first case had sharp corners, so I rounded them to avoid hurting the user.

Tight Fit

The PCB did not fit well, so I made the box bigger.

Sensor Opening

I added a small chamfer where the sensor enters so it goes in more easily.

Connection to My Final Project

This week joins the parts of Ancora that I made in the previous weeks. The sensor, the outputs, the Bluetooth connection, the app and the case now work as one bracelet.

Now the user can choose the output and use the exercise mode from the phone. The outputs also guide a breathing exercise.

Wearable Form

The sensor touches the skin and the case protects the board.

User Control

The app sets the output and the exercise mode.

Guided Breathing

The LED and the motor guide the user through the exercise.

Charging

The battery charges through the USB-C port of the ESP32-C3.

Maintenance

The glued lid can be removed to reach the circuit.

Downloadable Files