AI-Powered ECG Analysis from Wearables
ECG from Apple Watch Series 4+ or AliveCor KardiaMobile—single-channel recording, 30 seconds, 512 Hz. Sufficient for detecting atrial fibrillation and other rhythm disorders. Developer task—accept signal, process correctly, apply model without false negatives or regulatory violations.
Getting ECG Data
Apple Watch + HealthKit
Apple Watch Series 4+ records ECG via HKElectrocardiogram. Access through HealthKit:
import HealthKit
func fetchLatestECG() async throws -> (HKElectrocardiogram, [Double]) {
let ecgType = HKObjectType.electrocardiogramType()
let query = HKSampleQuery(
sampleType: ecgType,
predicate: nil,
limit: 1,
sortDescriptors: [NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)]
) { _, samples, error in
// handle
}
// Separate subquery for voltage data
let voltageQuery = HKElectrocardiogramQuery(ecg) { _, result in
switch result {
case .measurement(let measurement):
if let voltage = measurement.quantity(for: .appleWatchSimilarToLeadI) {
let microvolts = voltage.doubleValue(for: .volt()) * 1_000_000
voltageData.append(microvolts)
}
case .done: break
case .error(let error): print(error)
}
}
healthStore.execute(voltageQuery)
}
Apple returns raw signal in volts, selected Lead I (wrist). Sampling frequency—512 Hz, length—~15360 samples per 30 seconds.
Third-Party Devices: BLE + Protocol
AliveCor KardiaMobile, Withings Move ECG and similar transmit ECG via BLE with proprietary protocols. Most provide SDKs: KardiaMobile SDK for iOS/Android, Withings SDK. Without SDK—analyze BLE packets via CBCentralManager and reverse-engineer protocol (time-consuming, unreliable).
Signal Preprocessing: Without It, Model Fails
Raw ECG signal contains noise: baseline wander (isoline drift from breathing), muscle artifacts, electrical interference 50/60 Hz. Pre-processing before model input mandatory.
Bandpass filter 0.5–40 Hz removes baseline wander and high-frequency noise:
from scipy.signal import butter, filtfilt
def bandpass_filter(signal, fs=512, lowcut=0.5, highcut=40):
nyq = fs / 2
low = lowcut / nyq
high = highcut / nyq
b, a = butter(4, [low, high], btype='band')
return filtfilt(b, a, signal)
R-peak detection (Pan-Tompkins algorithm) needed for RR-interval calculation—basis for arrhythmia detection. Library neurokit2 implements Pan-Tompkins, BioSPPy. On mobile, implement natively: Swift via Accelerate framework (vDSP), Kotlin via KotlinDL or port scipy code via TFLite custom ops.
Models for Arrhythmia Detection
CNN for Rhythm Classification
Standard approach—1D CNN on 2.5–10 second signal window. Input tensor: [batch, time_steps, 1]. Architecture: several Conv1D → MaxPool → Dense → Softmax.
Public datasets: PhysioNet MIT-BIH Arrhythmia Database (48 dual-channel recordings), PTB-XL (21,799 clinical ECGs with 71 diagnoses). MIT-BIH available via wfdb library.
After training, convert to CoreML:
import coremltools as ct
spec = ct.convert(
torch_model,
inputs=[ct.TensorType(shape=(1, 2560, 1), dtype=np.float32)],
compute_precision=ct.precision.FLOAT16,
compute_units=ct.ComputeUnit.CPU_AND_NE
)
spec.save("ECGClassifier.mlpackage")
FLOAT16 quantization halves model size without significant accuracy loss for ECG classification. Neural Engine (NE) accelerates inference on A12+ devices.
Limitations of On-Device Analysis
Single-channel wrist ECG—not clinical 12-channel. Apple's sensitivity per their research: AF—99.3%, but specific rhythm. Other disorders (blocks, WPW) require 12-channel recording.
Regulatory Requirements — Most Important
If app claims disease diagnosis—it's a medical device (CE Class IIa in EU, FDA 510(k)/De Novo in USA). Development takes multiples longer due to clinical trial requirements, design control, software validation.
If app positioned as information only ("shows rhythm patterns, not diagnostic tool")—regulatory burden lower. All disclaimers must be on result screens, not just ToS.
Apple does this: each ECG result in Apple Health accompanied by "consult your doctor".
Development Process
Clarify regulatory strategy before development. Integrate with HealthKit or third-party SDK. Implement signal processing (filters, R-peak detection). Develop and validate ML model on public datasets. Convert to CoreML/TFLite. UI: ECG visualization, analysis result, mandatory disclaimers.
Timeframe Estimates
Basic AF detector with CoreML and HealthKit integration—3–5 weeks. Extended system with multiple arrhythmia types, clinical data validation—2–3 months. Full medical device with regulatory documentation—separate multi-month project.







