ECG and GSR code

well, I am interested in these values: [t=60s] HR=166bpm SDNN=15ms RMSSD=22ms pNN50=2.5% SCL=5.84uS SCLmed=5.16uS nSCR=12 frSCR=24.0/min ampSCR=1.41uS.
The values ​​for HR, RMSSD and SDNN are my problem. HR cannot be greater than 110 bpm, and RMSSD cannot be greater than SDNN. and if we look at what you got after running the code HR=166 bpm, and RMSSD= 22 ms which is greater than SDNN= 15 ms. I've been reading articles and the answer for these different values ​​would be that those R peaks, the peaks of the QRS complex in the ECG, are not being detected correctly, but I don't know what I could change in the code to get them all detected.

I am using an Arduino Uno Rev 3, an AD8232 ECG sensor and a Grove GSR.

Where in the code is HR read? I will force it to "78" (your HR) to see if we have the same output.

I do not see analogRead(HR); only analogRead(ECG) and analogRead(GSR)

The code doesn't read HR exactly, I record the ECG signal, then based on the recording I detect the heartbeat and calculate HR:

  if (ecg_integrat > prag_R && (acum_ms - ultim_R_ms) > REFRACTAR_MS) {
    if (ultim_R_ms > 0) {
      unsigned long RR = acum_ms - ultim_R_ms;

      if (RR > 300 && RR < 2000) {
        RR_buffer[RR_index] = (unsigned int)RR;
        RR_index = (RR_index + 1) % MAX_RR;
        if (RR_count < MAX_RR) RR_count++;
      }
    }
    ultim_R_ms = acum_ms;
  }
}
float media_RR = suma / n_valid;
float HR = 60000.0f / media_RR;

I am assuming the results of these calculations throw out the first value... as ecg_prev2 is used before it obtains a value... same with ecg_prev1...

  // Derivata
  float deriv = ecg_filt - ecg_prev2;
  ecg_prev2 = ecg_prev1;
  ecg_prev1 = ecg_filt;

Yes, it throws the first value to have this calculation in real time, the values ​​are constantly updated according to the signal that is recorded

Do you have the original, non-code, formula for each of these? Or, are you certain your code is calculating values correctly?

Can you introduce some "fake" (but real) data to see if these sketches calculate correctly?

I made this code after a matlab code (I leave it below). The idea is that I recorded these two signals with a BIOPAC device, I loaded the files into matlab and processed them calculating all these parameters and they were calculated correctly using the same formulas. Now I need to transpose that code from matlab to arduino, because I made a portable prototype that would record the two signals and calculate the parameters, but although the formulas are the same as in the matlab code, in arduino it doesn't calculate correctly as you saw.
’ll give you the standard definitions and formulas used in heart rate variability analysis, in clear notation:




The code from matlab:

%% 1. INCARCARE DATE
fisier = 'Bianca.txt';
Fs     = 2000;
data   = load(fisier);
N      = size(data,1);
t      = (0:N-1)' / Fs;
ecg_brut = data(:,1);
gsr_brut = data(:,2);

%% 2. SEGMENTARE IN 3 PERIOADE
L = floor(N/3);
index{1} = 1     : L;
index{2} = L+1   : 2*L;
index{3} = 2*L+1 : 3*L;
nume_perioada = {'Relaxare', 'Stres', 'Recuperare'};
durata_perioada = L/Fs;

%% 3. FILTRARE ECG
% Filtru median 
fer1 = round(0.2 * Fs); if mod(fer1,2)==0, fer1=fer1+1; end
fer2 = round(0.6 * Fs); if mod(fer2,2)==0, fer2=fer2+1; end
baseline = medfilt1(medfilt1(ecg_brut, fer1), fer2);
ecg_db   = ecg_brut - baseline;

% Notch 50 Hz si 100 Hz 
[b1, a1] = iirnotch(50/(Fs/2),  (50/(Fs/2))/35);
[b2, a2] = iirnotch(100/(Fs/2), (100/(Fs/2))/35);
ecg_db = filtfilt(b1, a1, ecg_db);
ecg_db = filtfilt(b2, a2, ecg_db);

% Low-pass 40 Hz 
[b_lp, a_lp] = butter(2, 40/(Fs/2), 'low');
ecg_filt = filtfilt(b_lp, a_lp, ecg_db);

%% 4. FILTRARE GSR + DECOMPOZITIE SCL/SCR
% Low-pass 5 Hz 
[bG, aG] = butter(4, 5/(Fs/2), 'low');
gsr_filt = filtfilt(bG, aG, gsr_brut);

% SCL = componenta tonica 
fer_scl = round(10 * Fs);
SCL     = movmean(gsr_filt, fer_scl);

% SCR = componenta fazica 
SCR = gsr_filt - SCL;
SCR = movmean(SCR, round(0.5*Fs));

%% 5. DETECTIE R-PEAKS (prag adaptiv pe percentila 99)
% Distanta minima 450 ms = max ~133 bpm, evita complet undele T
prag_R     = 0.6 * prctile(ecg_filt, 99);
min_dist_R = round(0.45 * Fs);

[~, R_locs] = findpeaks(ecg_filt, ...
                        'MinPeakHeight',   prag_R, ...
                        'MinPeakDistance', min_dist_R);

%% 6. DETECTIE SCR-uri
prag_SCR     = 0.05;
min_dist_SCR = round(1.0 * Fs);

[SCR_amp, SCR_locs] = findpeaks(SCR, ...
                                'MinPeakHeight',  prag_SCR, ...
                                'MinPeakDistance', min_dist_SCR);


%% 7. CALCUL HRV PE PERIOADE
disp(' ');
disp(' METRICI HRV PE PERIOADE ');
disp(' ');

for i = 1:3
    % Selecteaza R-peaks din perioada i
    Ri = R_locs(R_locs >= index{i}(1) & R_locs <= index{i}(end));
    
    % Calculeaza intervalele RR (ms)
    RR = diff(Ri) / Fs * 1000;
    
    med_RR = median(RR);
    RR_filt = RR(RR > 300 & RR < 2000 & RR > 0.8*med_RR & RR < 1.2*med_RR);
    
    % HR
    HR = 60000 / mean(RR_filt);
    
    % SDNN
    SDNN = std(RR_filt);
    
    % RMSSD
    dif_RR = diff(RR_filt);
    RMSSD = sqrt(mean(dif_RR.^2));
    
    % pNN50 
    NN50 = 0;
    for j = 1:length(dif_RR)
        if abs(dif_RR(j)) > 50
            NN50 = NN50 + 1;
        end
    end
    pNN50 = 100 * NN50 / length(dif_RR);
    
    % Afisare rezultate
    fprintf('Perioada: %s\n', nume_perioada{i});
    fprintf('  HR     = %.1f bpm\n', HR);
    fprintf('  SDNN   = %.1f ms\n', SDNN);
    fprintf('  RMSSD  = %.1f ms\n', RMSSD);
    fprintf('  pNN50  = %.2f %%\n', pNN50);
    fprintf('\n');
end

%% 8. CALCUL METRICI GSR PE PERIOADE
disp(' ');
disp('  METRICI GSR PE PERIOADE  ');
disp(' ');

for i = 1:3
    SCL_mediu = mean(SCL(index{i}));
    
    nr_SCR = 0;
    suma_amp = 0;
    for j = 1:length(SCR_locs)
        if SCR_locs(j) >= index{i}(1) && SCR_locs(j) <= index{i}(end)
            nr_SCR = nr_SCR + 1;
            suma_amp = suma_amp + SCR_amp(j);
        end
    end
    
    % Frecventa SCR
    SCR_frecv = nr_SCR / (durata_perioada/60);
    
    % Amplitudine medie SCR
    if nr_SCR > 0
        Amed_SCR = suma_amp / nr_SCR;
    else
        Amed_SCR = 0;
    end
    
    % Afisare rezultate
    fprintf('Perioada: %s\n', nume_perioada{i});
    fprintf('  SCL mediu     = %.3f uS\n', SCL_mediu);
    fprintf('  Frecv. SCR    = %.2f /min\n', SCR_frecv);
    fprintf('  Ampl. medie   = %.3f uS\n', Amed_SCR);
    fprintf('\n');
end

%% Grafice
culori = {'g', 'r', 'b'};
durata_zoom = 5;
N_zoom = durata_zoom * Fs;

%% FIGURA 1: ECG filtrat 
figure('Name', 'ECG filtrat');
for i = 1:3
    centru = index{i}(round(end/2));
    idx_zoom = (centru - round(N_zoom/2)) : (centru + round(N_zoom/2) - 1);
    t_zoom = (0:length(idx_zoom)-1) / Fs;
    
    subplot(3,1,i);
    plot(t_zoom, ecg_filt(idx_zoom), culori{i});
    grid on;
    xlabel('Timp (s)'); ylabel('Amplitudine (mV)');
    title(['ECG filtrat - ' nume_perioada{i}]);
end

%% FIGURA 2: ECG filtrat + R-peaks
figure('Name', 'ECG cu R-peaks');
for i = 1:3
    centru = index{i}(round(end/2));
    start_zoom = centru - round(N_zoom/2);
    stop_zoom  = centru + round(N_zoom/2) - 1;
    idx_zoom = start_zoom:stop_zoom;
    t_zoom = (0:length(idx_zoom)-1) / Fs;
    
    R_in_zoom = R_locs(R_locs >= start_zoom & R_locs <= stop_zoom);
    t_R = (R_in_zoom - start_zoom) / Fs;
    
    subplot(3,1,i);
    plot(t_zoom, ecg_filt(idx_zoom), culori{i}); hold on;
    plot(t_R, ecg_filt(R_in_zoom), 'ko', 'MarkerFaceColor', 'y');
    grid on;
    xlabel('Timp (s)'); ylabel('Amplitudine (mV)');
    title(['ECG + R-peaks - ' nume_perioada{i}]);
end

%% FIGURA 3: GSR brut 
figure('Name', 'GSR brut');
plot(t, gsr_brut, 'k');
hold on;
xline(index{2}(1)/Fs, 'r--', 'LineWidth', 1.5);
xline(index{3}(1)/Fs, 'r--', 'LineWidth', 1.5);
grid on;
xlabel('Timp (s)'); ylabel('Conductanta (\muS)');
title('GSR brut - semnal complet');
legend('GSR brut', 'Tranzitii perioade');

%% FIGURA 4: GSR filtrat 
figure('Name', 'GSR filtrat');
for i = 1:3
    t_seg = (0:length(index{i})-1) / Fs;
    subplot(3,1,i);
    plot(t_seg, gsr_filt(index{i}), culori{i});
    grid on;
    xlabel('Timp (s)'); ylabel('Conductanta (\muS)');
    title(['GSR filtrat - ' nume_perioada{i}]);
end

%% FIGURA 5: GSR cu SCL si SCR 
figure('Name', 'GSR - SCL si SCR');
for i = 1:3
    t_seg = (0:length(index{i})-1) / Fs;
    subplot(3,1,i);
    plot(t_seg, gsr_filt(index{i}), 'Color', [0.7 0.7 0.7]); hold on;
    plot(t_seg, SCL(index{i}), 'b', 'LineWidth', 1.5);
    plot(t_seg, SCR(index{i}) + mean(SCL(index{i})), 'm');
    grid on;
    xlabel('Timp (s)'); ylabel('Conductanta (\muS)');
    title(['GSR cu SCL si SCR - ' nume_perioada{i}]);
    legend('GSR filtrat', 'SCL', 'SCR ');
end

%% FIGURA 6: BAR CHARTS

HR_arr = zeros(1,3); SDNN_arr = zeros(1,3);
RMSSD_arr = zeros(1,3); pNN50_arr = zeros(1,3);
SCL_arr = zeros(1,3); SCRfr_arr = zeros(1,3); SCRamp_arr = zeros(1,3);

for i = 1:3
    Ri = R_locs(R_locs >= index{i}(1) & R_locs <= index{i}(end));
    RR = diff(Ri) / Fs * 1000;
    med_RR = median(RR);
    RR_filt = RR(RR > 300 & RR < 2000 & RR > 0.8*med_RR & RR < 1.2*med_RR);
    
    HR_arr(i) = 60000 / mean(RR_filt);
    SDNN_arr(i) = std(RR_filt);
    dif_RR = diff(RR_filt);
    RMSSD_arr(i) = sqrt(mean(dif_RR.^2));
    pNN50_arr(i) = 100 * sum(abs(dif_RR) > 50) / length(dif_RR);
    
    SCL_arr(i) = mean(SCL(index{i}));
    SCR_in_seg = SCR_locs(SCR_locs >= index{i}(1) & SCR_locs <= index{i}(end));
    SCRfr_arr(i) = length(SCR_in_seg) / (durata_perioada/60);
    if ~isempty(SCR_in_seg)
        SCRamp_arr(i) = mean(SCR(SCR_in_seg));
    end
end

%% FIGURA 6.1: BAR CHARTS HRV
figure('Name', 'Metrici HRV');

subplot(2,2,1); bar(HR_arr); title('HR (bpm)');
set(gca, 'XTickLabel', nume_perioada); grid on;

subplot(2,2,2); bar(SDNN_arr); title('SDNN (ms)');
set(gca, 'XTickLabel', nume_perioada); grid on;

subplot(2,2,3); bar(RMSSD_arr); title('RMSSD (ms)');
set(gca, 'XTickLabel', nume_perioada); grid on;

subplot(2,2,4); bar(pNN50_arr); title('pNN50 (%)');
set(gca, 'XTickLabel', nume_perioada); grid on;

sgtitle('Metrici HRV pe cele 3 perioade');

%% FIGURA 6.2: BAR CHARTS - metrici GSR
figure('Name', 'Metrici GSR');

subplot(1,3,1); bar(SCL_arr); title('SCL mediu (\muS)');
set(gca, 'XTickLabel', nume_perioada); grid on;

subplot(1,3,2); bar(SCRfr_arr); title('Frecventa SCR (/min)');
set(gca, 'XTickLabel', nume_perioada); grid on;

subplot(1,3,3); bar(SCRamp_arr); title('Amplitudine SCR (\muS)');
set(gca, 'XTickLabel', nume_perioada); grid on;

sgtitle('Metrici GSR pe cele 3 perioade');

Heh... The English language has a saying that pertains to the formulae you posted: "It's all Greek to me." (meaning: I do not understand it). Same goes for me with MatLab. So, back to the Arduino code.

I see two pins in use on the Arduino...

It seems they are normally "HIGH", and active when "LOW"...

  // ECG la 250 Hz
  if (digitalRead(PIN_LO_PLUS) == 0 && digitalRead(PIN_LO_MINUS) == 0) {

However, your code configures them as INPUT which relies on an external "pulling" resistor... (this resistor may be on the device connected to these pins)

  pinMode(PIN_LO_PLUS, INPUT);
  pinMode(PIN_LO_MINUS, INPUT);

Normally, pins showing HIGH inactive, LOW active are configured with INPUT_PULLUP to keep the pins HIGH during inactivity... like this...

  pinMode(PIN_LO_PLUS, INPUT_PULLUP);
  pinMode(PIN_LO_MINUS, INPUT_PULLUP);

Do you know the device connected to these DIO pins? If the device/module connected to each of these pins are not "tied" to the "HIGH" state or "LOW" state, the state of each pin might be "unknown" or floating... possibly starting the readings at the wrong time. I just want to verify some device is connected to these two pins.

Would you make a wiring diagram of the devices you are using? Pencil drawing or computer drawing, identifying the devices, the pins used and connecting wires.

So, this "250Hz" timer is dependent on the two pins mentioned above... as the timer must wait for both pins to be LOW.

  // ECG la 250 Hz
  if (digitalRead(PIN_LO_PLUS) == 0 && digitalRead(PIN_LO_MINUS) == 0) {
    if (acum_us - ultim_us_ecg >= PERIOADA_ECG_US) {
      ultim_us_ecg = acum_us;
      proceseazaECG(acum_ms);
    }
  }

... which means ultim_us_ecg does not receive a value, and proceseazaECG(acum_ms); does not get called if the pins are doing something unintended.

However; the 10Hz GSR does not get blocked by the absence of both pins' LOW states.

  // GSR la 10 Hz
  if (acum_us - ultim_us_gsr >= PERIOADA_GSR_US) {
    ultim_us_gsr = acum_us;
    proceseazaGSR(acum_ms);
  }

[edit] I noticed RR_count is directly effected by either of the two pins (10 and 11) not being LOW.

I see in this example sketch from the AD8232 that the device uses "INPUT" for pin configuration (so the board pulls the pin LOW during inactivity). The example code waits for either pin/probe to read "HIGH" to be active... which seems to mean the analog input should be read.

void setup() {
  // initialize the serial communication:
  Serial.begin(9600);
  pinMode(10, INPUT); // Setup for leads off detection LO +
  pinMode(11, INPUT); // Setup for leads off detection LO -

}

void loop() {
  
  if((digitalRead(10) == 1)||(digitalRead(11) == 1)){
    Serial.println('!');
  } else{
    // send the value of analog input 0:
      Serial.println(analogRead(A0));
  }
  //Wait for a bit to keep serial data from saturating
  delay(1);
}

More strange things are in the code, for example, these two lines...

  float gsr_filt = gsr_lp_prev + ALPHA_GSR * (gsr_brut - gsr_lp_prev);
  gsr_lp_prev = gsr_filt;

... can be written without gsr_filt like this...

  gsr_lp_prev  = gsr_lp_prev + ALPHA_GSR * (gsr_brut - gsr_lp_prev);

... because gsr_filt is used only in proceseazaGSR() and can be replaced by gsr_lp_prev

This leads me to believe there is a bunch of unnecessary (sloppy) code.

So... would you show a link to the original code?

The ECG module might require 3.3vdc for power rather than 5.0vdc...which it can get 3.3v power from the Arduino 3.3v pin.

The ECG LEAD OFF pins (LO+ and LO-) might be expecting only 3.3v when the leads are not connected.

[edit]
Code dump, OP diappeared.

code
// https://forum.arduino.cc/t/ecg-and-gsr-code/1442375/30

// ============================================================
//                     1. CONFIGURARI GENERALE
// ============================================================
const int PIN_GSR = A1;
const int PIN_ECG = A0; // ECG sensor analog pin
const int PIN_LO_PLUS  = 10; // ECG Lead Off POS pin // 1 = NOT CONNECTED
const int PIN_LO_MINUS = 11; // ECG Lead Off NEG pin // 1 = NOT CONNECTED
const unsigned long PERIOADA_ECG_US = 4000;    // 250 Hz in microseconds
const unsigned long PERIOADA_GSR_US = 100000;  // 10 Hz in microseconds
const unsigned long INTERVAL_AFISARE_MS = 10000; // display interval 10s
unsigned long ultim_afisare_ms = 0; // last display timer
unsigned long start_ms = 0; // start timer
const bool DEBUG_ECG = true; // debug flag
unsigned long ultim_debug_ecg_ms = 0; // last debug ecg timer
// ============================================================
//             2. FILTRARE ECG
// ============================================================
float ecg_hp_prev_in  = 0;
float ecg_hp_prev_out = 0;
const float ALPHA_HP = 0.987f;   // trece-sus 0.5 Hz
float ecg_lp_prev = 0;
const float ALPHA_LP = 0.36f;    // trece-jos 40 Hz
float ecg_prev1 = 0;
float ecg_prev2 = 0;
// ============================================================
//        3. DETECTIE R-PEAK (Pan-Tompkins cu integrare)
// ============================================================
const int FER_INT = 20;
float int_buffer[FER_INT];
int int_index = 0;
float int_suma = 0;
float ecg_integrat = 0;
float prag_R = 0.0f;
float ecg_max_recent = 0.0f;
const float COEF_PRAG = 0.35f;
const unsigned long REFRACTAR_MS = 350;
unsigned long ultim_R_ms = 0;
const int MAX_RR = 200;
unsigned int RR_buffer[MAX_RR];
int RR_index = 0;
int RR_count = 0;
// ============================================================
//             4. GSR cu CALIBRARE EMPIRICA
// ============================================================
float gsr_lp_prev = 0;
const float ALPHA_GSR = 0.76f;
const unsigned long DURATA_CALIBRARE_MS = 30000UL;
bool GSR_calibrat = false;
float ADC_GSR_baseline = 0;
float ADC_calib_suma = 0;
unsigned long ADC_calib_n = 0;
float SCALA_GSR = 0.1f;
const int FER_SCL = 100;
float SCL_buffer[FER_SCL];
int SCL_index = 0;
float SCL_suma = 0;
float SCL_curent = 0;
float SCL_acumulator = 0;
unsigned long SCL_n = 0;
float SCR_prag = 0.1f;
const unsigned long REFRACTAR_SCR_MS = 1000;
unsigned long ultim_SCR_ms = 0;
float SCR_prev = 0;
unsigned int SCR_count = 0;
float SCR_amp_suma = 0;
// ============================================================
//             5. VARIABILE TIMP
// ============================================================
unsigned long ultim_us_ecg = 0;
unsigned long ultim_us_gsr = 0;
// ============================================================
//                       SETUP
// ============================================================
void setup() {
  Serial.begin(9600);
  pinMode(PIN_LO_PLUS, INPUT);
  pinMode(PIN_LO_MINUS, INPUT);
  for (int i = 0; i < FER_SCL; i++)
    SCL_buffer[i] = 0;
  for (int i = 0; i < FER_INT; i++)
    int_buffer[i] = 0;
  Serial.println(F("============================================"));
  Serial.println(F(" MONITOR STRES - HRV + GSR (continuu) ")); // heart rate variability
  Serial.println(F("============================================"));
  Serial.println(F("Plasati electrozii FERM."));
  Serial.println(F("Stati nemiscat - mai ales primele 30 sec!"));
  Serial.println(F("Start in 5 secunde..."));
  delay(5000);
  start_ms = millis();
  ultim_afisare_ms = millis();
  ultim_debug_ecg_ms = millis();
  ultim_us_ecg = micros();
  ultim_us_gsr = micros();
  Serial.println(F(">>> START - calibrare GSR primele 30 sec"));
}

// ============================================================
//                       LOOP PRINCIPAL
// ============================================================
void loop() {
  unsigned long acum_us = micros();
  unsigned long acum_ms = millis();
  // ECG la 250 Hz
  if (digitalRead(PIN_LO_PLUS) == 0 && digitalRead(PIN_LO_MINUS) == 0) {
    if (acum_us - ultim_us_ecg >= PERIOADA_ECG_US) { // duration longer than 0.004 seconds // 250 Hz
      ultim_us_ecg = acum_us; // store current time
      proceseazaECG(acum_ms);
    }
  }
  // GSR la 10 Hz
  if (acum_us - ultim_us_gsr >= PERIOADA_GSR_US) { // duration longer than 0.1 seconds // 10 Hz
    ultim_us_gsr = acum_us;
    proceseazaGSR(acum_ms);
  }
  // Calibrare GSR la 30 sec
  if (!GSR_calibrat && acum_ms - start_ms >= DURATA_CALIBRARE_MS) {
    finalizeazaCalibrareGSR();
  }
  // DEBUG ECG la fiecare 3 sec
  if (DEBUG_ECG && acum_ms - ultim_debug_ecg_ms >= 3000) {
    ultim_debug_ecg_ms = acum_ms;
    Serial.print(F("  [ECG_DBG] integrat="));
    Serial.print(ecg_integrat, 6);
    Serial.print(F(" max="));
    Serial.print(ecg_max_recent, 6);
    Serial.print(F(" prag="));
    Serial.print(prag_R, 6);
    Serial.print(F(" RR_count="));
    Serial.println(RR_count);
  }
  // Afisare metrici la fiecare 10 sec
  if (acum_ms - ultim_afisare_ms >= INTERVAL_AFISARE_MS) { // every 10 seconds
    ultim_afisare_ms = acum_ms; // restart timer
    afiseazaMetrici(acum_ms); // display metrics
  }
}

// ============================================================
//                   PROCESARE ECG (Pan-Tompkins)
// ============================================================
void proceseazaECG(unsigned long acum_ms) {
  float ecg_brut = analogRead(PIN_ECG) * (5.0f / 1023.0f); // voltage reading 0v to 5v ?? why V and not bits??
  // Trece-sus 0.5 Hz
  float ecg_hp = ALPHA_HP * (ecg_hp_prev_out + ecg_brut - ecg_hp_prev_in);
  ecg_hp_prev_in  = ecg_brut;
  ecg_hp_prev_out = ecg_hp;
  // Trece-jos 40 Hz
  ecg_lp_prev = ecg_lp_prev + ALPHA_LP * (ecg_hp - ecg_lp_prev);
  // Derivata
  float deriv = ecg_lp_prev - ecg_prev2;
  ecg_prev2 = ecg_prev1;
  ecg_prev1 = ecg_lp_prev;
  // Patrat
  float ecg_pat = deriv * deriv;
  // INTEGRARE pe fereastra 80 ms
  int_suma -= int_buffer[int_index];
  int_buffer[int_index] = ecg_pat;
  int_suma += ecg_pat;
  int_index = (int_index + 1) % FER_INT;
  ecg_integrat = int_suma / FER_INT;
  // Prag adaptiv cu PROTECTIE ANTI-ARTEFACT MISCARE
  // (limitam cresterea brusca a maximului la max 1.5x valoarea curenta)
  if (ecg_integrat > ecg_max_recent) {
    float nou_max = ecg_integrat;
    if (ecg_max_recent > 0 && nou_max > 1.5f * ecg_max_recent) {
      nou_max = 1.5f * ecg_max_recent;
    }
    ecg_max_recent = nou_max;
  } else {
    ecg_max_recent *= 0.9995f;
  }
  prag_R = COEF_PRAG * ecg_max_recent;

  // Detectie R-peak SIMPLA (fara filtrare RR succesive)
  // Filtrarea artefactelor se face la afisare, prin mediana ±20%
  detectRpeak(acum_ms);
}

// ============================================================
// Detectie R-peak SIMPLA (fara filtrare RR succesive)
// Filtrarea artefactelor se face la afisare, prin mediana ±20%
// ============================================================
void detectRpeak(unsigned long acum_ms) {
  if (ecg_integrat > prag_R && (acum_ms - ultim_R_ms) > REFRACTAR_MS) {
    if (ultim_R_ms > 0) {
      unsigned long RR = acum_ms - ultim_R_ms;
      if (RR > 300 && RR < 2000) {
        RR_buffer[RR_index] = (unsigned int)RR;
        RR_index = (RR_index + 1) % MAX_RR;
        if (RR_count < MAX_RR) RR_count++;
      }
    }
    ultim_R_ms = acum_ms;
  }
}

// ============================================================
//                   PROCESARE GSR
// ============================================================
void proceseazaGSR(unsigned long acum_ms) {
  int adc = analogRead(PIN_GSR);
  if (!GSR_calibrat) {
    ADC_calib_suma += adc;
    ADC_calib_n++;
    return;
  }
  // Conversie liniara empirica
  float gsr_brut = 5.0f + ((float)ADC_GSR_baseline - (float)adc) * SCALA_GSR;
  if (gsr_brut < 0.5f)
    gsr_brut = 0.5f;
  if (gsr_brut > 30.0f)
    gsr_brut = 30.0f;

  // Trece-jos 5 Hz
  gsr_lp_prev = gsr_lp_prev + ALPHA_GSR * (gsr_brut - gsr_lp_prev);
  // SCL = media mobila pe 10 sec
  SCL_suma -= SCL_buffer[SCL_index];
  SCL_buffer[SCL_index] = gsr_lp_prev;
  SCL_suma += gsr_lp_prev;
  SCL_index = (SCL_index + 1) % FER_SCL;
  SCL_curent = SCL_suma / FER_SCL;
  SCL_acumulator += SCL_curent;
  SCL_n++;

  // SCR = componenta fazica
  float SCR = gsr_lp_prev - SCL_curent;
  // Detectie SCR
  if (SCR > SCR_prag && SCR_prev <= SCR_prag &&
      (acum_ms - ultim_SCR_ms) > REFRACTAR_SCR_MS) {
    SCR_count++;
    SCR_amp_suma += SCR;
    ultim_SCR_ms = acum_ms;
  }
  SCR_prev = SCR;
}

// ============================================================
//             FINALIZARE CALIBRARE GSR
// ============================================================
void finalizeazaCalibrareGSR() {
  if (ADC_calib_n > 5) {
    ADC_GSR_baseline = ADC_calib_suma / ADC_calib_n;
    if (ADC_GSR_baseline > 500) {
      SCALA_GSR = -0.1f;
    } else {
      SCALA_GSR = 0.1f;
    }
    SCR_prag = 0.1f;
  }
  GSR_calibrat = true;
  Serial.println();
  Serial.print(F(">>> Calibrare GSR finalizata. ADC baseline = "));
  Serial.print(ADC_GSR_baseline, 0);
  Serial.print(F(", SCALA = "));
  Serial.println(SCALA_GSR, 3);
  Serial.println();
}
// ============================================================
//             AFISARE METRICI CONTINUU
// ============================================================
void afiseazaMetrici(unsigned long acum_ms) {
  unsigned long timp_total = (acum_ms - start_ms) / 1000;
  Serial.print(F("[t="));
  Serial.print(timp_total);
  Serial.print(F("s] "));
  // ====== HRV ====== heart rate variability
  if (RR_count < 3) {
    Serial.print(F("HR=-- (astept R-peaks) "));
  } else {
    // Mediana RR (filtrare ±20% - identic cu MATLAB)
    float med_RR = medianaRR();
    float suma = 0;
    int n_valid = 0;
    for (int i = 0; i < RR_count; i++) {
      float rr = RR_buffer[i];
      if (rr > 0.8f * med_RR && rr < 1.2f * med_RR) {
        suma += rr;
        n_valid++;
      }
    }
    if (n_valid >= 3) {
      float media_RR = suma / n_valid;
      float HR = 60000.0f / media_RR;
      // SDNN
      float ss = 0;
      for (int i = 0; i < RR_count; i++) {
        float rr = RR_buffer[i];
        if (rr > 0.8f * med_RR && rr < 1.2f * med_RR) {
          ss += (rr - media_RR) * (rr - media_RR);
        }
      }
      float SDNN = sqrt(ss / n_valid); // standard deviation of NN (R - R) intervals
      // RMSSD si pNN50 // root mean square of successive differences //
      float ss_dif = 0;
      int n_dif = 0;
      int NN50 = 0; // NN (R-R) intervals of 50ms
      float rr_prev = -1;
      for (int i = 0; i < RR_count; i++) {
        float rr = RR_buffer[i];
        if (rr > 0.8f * med_RR && rr < 1.2f * med_RR) {
          if (rr_prev > 0) {
            float d = rr - rr_prev;
            ss_dif += d * d;
            if (fabs(d) > 50) NN50++;
            n_dif++;
          }
          rr_prev = rr;
        }
      }
      float RMSSD = (n_dif > 0) ? sqrt(ss_dif / n_dif) : 0;
      float pNN50 = (n_dif > 0) ? (100.0f * NN50 / n_dif) : 0; // NN50 divided by total NN (R-R) intervals
      Serial.print(F("HR=")); Serial.print(HR, 0); Serial.print(F("bpm "));
      Serial.print(F("SDNN=")); Serial.print(SDNN, 0); Serial.print(F("ms "));
      Serial.print(F("RMSSD=")); Serial.print(RMSSD, 0); Serial.print(F("ms "));
      Serial.print(F("pNN50=")); Serial.print(pNN50, 1); Serial.print(F("% "));
    } else {
      Serial.print(F("HR=-- "));
    }
  }
  // ====== GSR ======
  if (!GSR_calibrat) {
    Serial.print(F("GSR=calibrare..."));
  } else {
    float SCL_mediu = (SCL_n > 0) ? (SCL_acumulator / SCL_n) : 0;
    float durata_min = (timp_total > 30) ? (timp_total - 30) / 60.0f : 0.001f;
    float SCR_frecv = SCR_count / durata_min;
    float SCR_amed  = (SCR_count > 0) ? (SCR_amp_suma / SCR_count) : 0;
    Serial.print(F("SCL=")); Serial.print(SCL_curent, 2); Serial.print(F("uS "));
    Serial.print(F("SCLmed=")); Serial.print(SCL_mediu, 2); Serial.print(F("uS "));
    Serial.print(F("nSCR=")); Serial.print(SCR_count); Serial.print(F(" "));
    Serial.print(F("frSCR=")); Serial.print(SCR_frecv, 1); Serial.print(F("/min "));
    Serial.print(F("ampSCR=")); Serial.print(SCR_amed, 2); Serial.print(F("uS"));
  }
  Serial.println();
}
// ============================================================
//                   FUNCTII AJUTATOARE
// ============================================================
float medianaRR() {
  unsigned int copie[MAX_RR];
  for (int i = 0; i < RR_count; i++)
    copie[i] = RR_buffer[i];
  for (int i = 0; i < RR_count - 1; i++) {
    for (int j = 0; j < RR_count - 1 - i; j++) {
      if (copie[j] > copie[j + 1]) {
        unsigned int tmp = copie[j];
        copie[j] = copie[j + 1];
        copie[j + 1] = tmp;
      }
    }
  }
  if (RR_count % 2 == 1) {
    return copie[RR_count / 2];
  } else {
    return (copie[RR_count / 2 - 1] + copie[RR_count / 2]) / 2.0f;
  }
}
diagram.json for wokwi

{
  "version": 1,
  "author": "foreignpigdog x",
  "editor": "wokwi",
  "parts": [
    { "type": "wokwi-arduino-nano", "id": "nano", "top": -4.8, "left": -38.9, "attrs": {} },
    {
      "type": "wokwi-slide-switch",
      "id": "sw1",
      "top": -84.8,
      "left": 48.5,
      "rotate": 90,
      "attrs": { "value": "" }
    },
    {
      "type": "wokwi-slide-switch",
      "id": "sw2",
      "top": -46.4,
      "left": 48.5,
      "rotate": 90,
      "attrs": { "value": "" }
    },
    { "type": "wokwi-potentiometer", "id": "pot1", "top": -87.7, "left": 191.8, "attrs": {} },
    { "type": "wokwi-potentiometer", "id": "pot2", "top": -87.7, "left": 115, "attrs": {} },
    {
      "type": "wokwi-text",
      "id": "text1",
      "top": -105.6,
      "left": 134.4,
      "attrs": { "text": "ECG" }
    },
    {
      "type": "wokwi-text",
      "id": "text2",
      "top": -105.6,
      "left": 211.2,
      "attrs": { "text": "GSR" }
    },
    { "type": "wokwi-text", "id": "text3", "top": -48, "left": 76.8, "attrs": { "text": "LO+" } },
    {
      "type": "wokwi-text",
      "id": "text4",
      "top": -86.4,
      "left": 76.8,
      "attrs": { "text": "LO-" }
    }
  ],
  "connections": [
    [ "nano:11", "sw1:2", "green", [ "v0" ] ],
    [ "nano:10", "sw2:2", "green", [ "v0" ] ],
    [ "pot1:SIG", "nano:A0", "green", [ "v96", "h-221.2" ] ],
    [ "pot2:SIG", "nano:A1", "green", [ "v86.4", "h-134.8" ] ],
    [ "pot1:GND", "nano:GND.3", "black", [ "v0" ] ],
    [ "pot2:GND", "nano:GND.3", "black", [ "v0" ] ],
    [ "pot2:VCC", "nano:5V.2", "red", [ "v0" ] ],
    [ "pot1:VCC", "nano:5V.2", "red", [ "v0" ] ],
    [ "nano:GND.3", "sw2:3", "black", [ "h-76.8", "v-38.6" ] ],
    [ "sw2:3", "sw1:3", "black", [ "h-9.6", "v-38.2" ] ],
    [ "nano:5V.2", "sw2:1", "red", [ "h-86.4", "v-76.8" ] ],
    [ "sw2:1", "sw1:1", "red", [ "h-19.2", "v-38.4" ] ]
  ],
  "dependencies": {}
}