|
| 1 | +import numpy as np |
| 2 | +import time |
| 3 | +from pylsl import StreamInlet, resolve_stream |
| 4 | +from scipy.signal import find_peaks |
| 5 | + |
| 6 | +# Resolve the LSL stream |
| 7 | +print("Looking for an LSL stream...") |
| 8 | +streams = resolve_stream('name', 'BioAmpDataStream') # Assuming the stream type is ECG |
| 9 | + |
| 10 | +# Create an inlet to read from the stream |
| 11 | +inlet = StreamInlet(streams[0]) |
| 12 | + |
| 13 | +# Function to filter ECG signal (simple bandpass filter) |
| 14 | +def filter_signal(signal): |
| 15 | + return signal |
| 16 | + |
| 17 | +# Function to detect heartbeats using peak detection |
| 18 | +def detect_heartbeats(ecg_data, sampling_rate): |
| 19 | + filtered_signal = filter_signal(ecg_data) |
| 20 | + |
| 21 | + # Detect peaks (R-peaks in ECG) |
| 22 | + peaks, _ = find_peaks(filtered_signal, distance=sampling_rate * 0.6) # Assuming minimum 600 ms between heartbeats |
| 23 | + |
| 24 | + return peaks |
| 25 | + |
| 26 | +# Sampling frequency (adjust to your actual stream) |
| 27 | +sampling_rate = 250 # Hz (example: 250 samples per second) |
| 28 | + |
| 29 | +# Collect ECG data and detect heartbeats |
| 30 | +window_size = sampling_rate * 5 # 5 seconds of data |
| 31 | +ecg_buffer = [] |
| 32 | + |
| 33 | +while True: |
| 34 | + # Get a new sample from the stream |
| 35 | + sample, timestamp = inlet.pull_sample() |
| 36 | + |
| 37 | + # Append the sample to the buffer |
| 38 | + ecg_buffer.append(sample[0]) # Assuming ECG data is in the first channel |
| 39 | + |
| 40 | + # Keep buffer size fixed |
| 41 | + if len(ecg_buffer) > window_size: |
| 42 | + ecg_buffer = ecg_buffer[-window_size:] |
| 43 | + |
| 44 | + # Detect heartbeats every window |
| 45 | + if len(ecg_buffer) == window_size: |
| 46 | + heartbeats = detect_heartbeats(ecg_buffer, sampling_rate) |
| 47 | + if heartbeats.size > 0: |
| 48 | + print(f"Heartbeats detected at positions: {heartbeats}") |
| 49 | + # Calculate heartbeat rate (bpm) |
| 50 | + rr_intervals = np.diff(heartbeats) / sampling_rate |
| 51 | + bpm = 60 / np.mean(rr_intervals) |
| 52 | + print(f"Heart rate: {bpm:.2f} bpm") |
| 53 | + |
| 54 | + time.sleep(0.01) # Adjust to control the data rate |
0 commit comments