MATLAB: Real-time heart rate calculation

heart ratephonocardiographreal timestethoscope

I have a real-time(phonocardiograph) plot which displays data from an electronic stethoscope via the COM port. I am trying to calculate the heart rate but having little success. I have created a uicontrol on the figure to display the BPM and have included the formulas to count the peak signals(beat_count). At the momement 'BPM:' displays on the plot figure but without a value so I am unable to get any BPM_avg reading.
a = arduino('COM4','Due');
y=0;
hPlot = plot(NaN);
intervalSize = 200;
currentInterval = 200;
t = 1; % number of samples
atInterval = 1;
beat_count = 0;
quitbutton = uicontrol('style','pushbutton',...
'string','Quit', ...
'fontsize',12, ...
'position',[10,2,50,20], ...
'callback','quitit=1;close');
quitit = 0;
bpmtext = uicontrol('style', 'text',...
'string', ['BPM: '],...
'fontsize', 12,...
'position', [80, 2, 100, 20]);
while(1)
k = 1;
while(t<currentInterval)
b=readVoltage(a, 'A0');
y=[y,b];
if ishandle(hPlot)
set(hPlot, 'YData', y);
else
break; % break out of the loop
end
xlabel('Samples')
ylabel('Voltage')
title('Phonocardiogram')
axis([currentInterval - intervalSize,currentInterval,0,3]);
%grid
t=t+k;
pause(0.002)
end
for m = 2 : length(b)-1
if(b(m) > b(m-1) & b(m) > b(m+1) & b(m) > 2.4)
%disp('Prominant peak found');
beat_count = beat_count + 1;
set(bpmtext, 'string', ['BPM: ',...
num2str(BPM_avg,4)]);
end
end
currentInterval = currentInterval + intervalSize;
atInterval = atInterval + 1;
if ~ishandle(hPlot)
break;
end
fs = 500;
N = length(b);
duration_in_seconds = N/fs;
duration_in_minutes = duration_in_seconds/60;
BPM_avg = beat_count/duration_in_minutes;
end

Best Answer

bilal - it doesn't look like BPM_avg is defined before you try and use it, so I'm surprised that you are not getting an error when you call
set(bpmtext, 'string', ['BPM: ', num2str(BPM_avg,4)]);
Also, why is the above in a for loop that does not do anything to BPM_avg
for m = 2 : length(b)-1
if(b(m) > b(m-1) & b(m) > b(m+1) & b(m) > 2.4)
%disp('Prominant peak found');
beat_count = beat_count + 1;
set(bpmtext, 'string', ['BPM: ',num2str(BPM_avg,4)]);
end
end
I think that that is part of the problem - BPM_avg is not being set or updated when it should be. Why not update it when you receive the data from the Arduino instead having this for loop outside of the while loop?