# Periodically samples an analog ECG signal from AD8232 front-end and monitors lead-off status.

from machine import Pin, ADC, Timer
import time

# 1. Analog ECG input and sampling configuration
# Analog output of AD8232 connected to ADC channel 2 (GP28)
ECG = ADC(28)

# Sampling period in milliseconds (20 ms corresponds to 50 Hz sampling frequency)
fs = 20  # ms

# Lead-off detection pins (AD8232 sets HIGH when an electrode is disconnected)
LOminus = Pin(17, Pin.IN, Pin.PULL_DOWN)
LOplus = Pin(18, Pin.IN, Pin.PULL_DOWN)

# Lead attachment status (True = electrodes properly connected)
leadsStateOK = True

# Conversion factor from raw 16-bit integer (0-65535) to voltage (0-3.3V)
conversionRate = 3.3 / 65535

# 2. Hardware timer callback function for periodic sampling
def sampleECG(timer):
    """
    Called periodically by hardware timer with exact period fs (20 ms).
    Reads instantaneous analog voltage and outputs formatted data string
    compatible with UBI Serial Plotter: /*voltage,leadsState*/
    """
    value = ECG.read_u16()
    voltage = value * conversionRate
    print(f"/*{voltage:.4f},{1 if leadsStateOK else 0}*/")

# 3. Initialize and start periodic timer
ECGtimer = Timer(mode=Timer.PERIODIC, period=fs, callback=sampleECG)

print("ECG sampling started (fs = 50 Hz)...")

# 4. Main loop monitoring electrode lead-off status
while True:
    if LOminus.value() == 1 or LOplus.value() == 1:
        if leadsStateOK:
            leadsStateOK = False
            print("# WARNING: Electrodes disconnected or poor skin contact!")
    elif LOminus.value() == 0 and LOplus.value() == 0:
        if not leadsStateOK:
            leadsStateOK = True
            print("# Electrodes properly connected.")
            
    time.sleep(0.05)
