# ProtoCentral ST1VAFE3BX Arduino Library

[![Arduino Lint](https://github.com/Protocentral/protocentral_st1vafe3bx_arduino/actions/workflows/arduino-lint.yml/badge.svg)](https://github.com/Protocentral/protocentral_st1vafe3bx_arduino/actions/workflows/arduino-lint.yml)
[![Compile Examples](https://github.com/Protocentral/protocentral_st1vafe3bx_arduino/actions/workflows/compile-examples.yml/badge.svg)](https://github.com/Protocentral/protocentral_st1vafe3bx_arduino/actions/workflows/compile-examples.yml)

Arduino library for the ProtoCentral ST1VAFE3BX breakout board — a combined biopotential (vAFE) and motion sensor based on the STMicroelectronics ST1VAFE3BX.

## Don't have one? [Buy it here](https://protocentral.com/)

![ST1VAFE3BX Breakout](assets/protocentral_st1vafe3bx.jpg)

The ST1VAFE3BX is an ultra-low-power biosensor that integrates a single-channel vertical analog front-end (vAFE) for biopotential signals (ECG, EMG, EEG) together with a 3-axis MEMS accelerometer, an on-chip Machine Learning Core (MLC), and a Finite State Machine (FSM) for edge-AI motion classification. The vAFE provides programmable gain and input impedance, making it suitable for dry-electrode and wearable applications. This Arduino library wraps the [official ST platform-independent driver](https://github.com/STMicroelectronics/st1vafe3bx-pid) behind a clean C++ API.

## Features

- Single-channel differential vAFE for biopotentials (ECG / EMG / EEG)
  - Programmable gain: 2x, 4x, 8x, 16x
  - Programmable input impedance: 100 MΩ to 1 GΩ
  - 12-bit ADC, ODR up to 3840 Hz
- 3-axis accelerometer
  - ±2 g / ±4 g / ±8 g / ±16 g full-scale
  - ODR from 1.875 Hz to 7680 Hz
- On-chip Machine Learning Core (MLC) for motion classification
- I²C interface, 3.3 V operation
- Works with Arduino, ESP32, Nano 33 BLE, and other 3.3 V boards

## Installation

### Arduino Library Manager (Recommended)
1. Open Arduino IDE
2. Go to **Sketch → Include Library → Manage Libraries**
3. Search for "ProtoCentral ST1VAFE3BX"
4. Click **Install**

### Manual Installation
1. Download or clone this repository
2. Copy to your Arduino libraries folder (`~/Documents/Arduino/libraries/`)
3. Restart the Arduino IDE

## Hardware Setup

### Pin Connections

| Signal | Arduino UNO | ESP32 | Nano 33 BLE |
|--------|-------------|-------|-------------|
| VCC    | 3.3 V       | 3.3 V | 3.3 V       |
| GND    | GND         | GND   | GND         |
| SDA    | A4          | 21    | SDA         |
| SCL    | A5          | 22    | SCL         |

I²C lines require 4.7 kΩ pull-ups to 3.3 V (already populated on the ProtoCentral breakout).

### Biopotential Electrode Connections

| Input  | Electrode  | Description                |
|--------|------------|----------------------------|
| AH_IN+ | LA         | Left arm (positive input)  |
| AH_IN− | RA         | Right arm (negative input) |

For EMG or EEG, place the differential pair across the muscle group or scalp site of interest. A reference / bias electrode tied to the board ground improves common-mode rejection.

## Quick Start

### Accelerometer

```cpp
#include <Wire.h>
#include "ST1VAFE3BX.h"

ST1VAFE3BX sensor;

void setup() {
    Serial.begin(115200);
    if (!sensor.begin()) {
        Serial.println("Sensor not detected!");
        while (1);
    }
    sensor.setAccelODR(AccelODR::Hz_60);
    sensor.setAccelFullScale(AccelFullScale::G_2);
}

void loop() {
    if (sensor.isAccelDataReady()) {
        AccelData a;
        sensor.readAccel(&a);
        Serial.print(a.x, 4); Serial.print(',');
        Serial.print(a.y, 4); Serial.print(',');
        Serial.println(a.z, 4);
    }
}
```

### ECG

```cpp
#include <Wire.h>
#include "ST1VAFE3BX.h"

ST1VAFE3BX sensor;

void setup() {
    Serial.begin(115200);
    if (!sensor.begin()) { while (1); }
    sensor.configureForECG();   // Differential, 1 GΩ, 4x gain
}

void loop() {
    Serial.println(sensor.readVAFE_mV(), 3);
    delay(4);  // ~250 Hz
}
```

## API Reference

### Constructor

```cpp
ST1VAFE3BX(TwoWire *wire = &Wire);
```

### Initialization

| Method | Description |
|--------|-------------|
| `begin(address)`  | Initialize the sensor on the given I²C address |
| `isConnected()`   | Returns `true` if the sensor responds |
| `reset()`         | Perform software reset |
| `getDeviceID()`   | Returns the WHO_AM_I register value |

### Accelerometer

| Method | Description |
|--------|-------------|
| `setAccelODR(odr)`         | Set output data rate |
| `setAccelFullScale(fs)`    | Set full scale (2 g / 4 g / 8 g / 16 g) |
| `isAccelDataReady()`       | Check for new sample |
| `readAccel(&data)`         | Read acceleration in g |

### vAFE (Biopotential)

| Method | Description |
|--------|-------------|
| `enableVAFE(enable)`         | Enable / disable the vAFE channel |
| `configureForECG()`          | One-call ECG preset (differential, 1 GΩ, 4× gain) |
| `setVAFE_InputMode(mode)`    | Set input mode |
| `setVAFE_Impedance(impedance)` | Set input impedance (100 MΩ – 1 GΩ) |
| `setVAFE_Gain(gain)`         | Set gain (2× / 4× / 8× / 16×) |
| `readVAFE_mV()`              | Read voltage in millivolts |

## Examples

| Example | Description |
|---------|-------------|
| `01.Accel`              | Stream X/Y/Z acceleration to Serial |
| `02.ECGHeartRate`       | ECG acquisition with simple heart-rate estimate |
| `03.ECGOpenView`        | ECG streaming in [ProtoCentral OpenView](https://github.com/Protocentral/protocentral_openview) packet format |
| `04.MotionIntensityMLC` | On-chip MLC classifying motion intensity (0–7) using the official ST UCF |
| `05.SmartRecorder`      | Context-aware ECG recorder — MLC watches for stillness, arms the vAFE only when still, streams ECG via OpenView, then re-arms |
| `06.HeartRateOnStill`   | Text-only variant of 05: drops to ECG when the subject is still and prints heart rate |

## Build Script (Arduino Nano 33 BLE)

A helper script for command-line builds is included:

```bash
./build.sh list                  # List available examples
./build.sh compile -e 01.Accel   # Compile an example
./build.sh upload  -e 01.Accel   # Compile and upload
./build.sh monitor               # Open the serial monitor
```

## Visualizing Output

Use the Arduino Serial Plotter for quick waveform inspection, or [ProtoCentral OpenView](https://github.com/Protocentral/protocentral_openview) for a richer multi-channel viewer (works with example `03.ECGOpenView`).

## Documentation

- [ST1VAFE3BX datasheet](assets/st1vafe3bx.pdf)
- [Application note AN6160](assets/an6160-st1vafe3bx-biosensor-with-vafe-vertical-analog-frontend-for-biopotential-signals-and-ultralowpower-accelerometer-with-ai-and-antialiasing-stmicroelectronics.pdf)
- [ST st1vafe3bx-pid driver](https://github.com/STMicroelectronics/st1vafe3bx-pid)

## License

**Hardware:** [Creative Commons Share-alike 4.0 International](http://creativecommons.org/licenses/by-sa/4.0/) ![CC-BY-SA-4.0](https://i.creativecommons.org/l/by-sa/4.0/88x31.png)

**Software:** [MIT License](http://opensource.org/licenses/MIT)

Copyright (c) 2025 ProtoCentral Electronics. See [LICENSE](LICENSE) for details.

## Support

- GitHub Issues: https://github.com/Protocentral/protocentral_st1vafe3bx_arduino/issues
- ProtoCentral: https://protocentral.com
