clc;
clearvars;
close all;
% fclose(instrfind);
dataRate = 5;
timeDatabuf = 0.2;
timeWinLength = 20;
plotWinLength = dataRate * timeWinLength ;
groupNum = 7;
frameLength = 13;
frameHead = '#S';
frameEnd = 'E*';
serialPort = serial('COM3','BaudRate',9600);
serialPort.InputBufferSize = frameLength * groupNum * dataRate * timeDatabuf;
serialPort.Timeout = 6000;
dataBufferSize = serialPort.InputBufferSize;
try
fopen(serialPort);
catch err
fclose(instrfind);
pause(0.1);
fopen(serialPort);
end
strChecker = blanks(2);
strBuffer = blanks(frameLength - 4 + 1);
dispBuffer = zeros(9,plotWinLength);
tAxes = -plotWinLength;
x = tAxes : 1 : tAxes + plotWinLength - 1;
t = x ./ dataRate;
channelNum = 1;
iStr = 1;
iStrBuf = 1;
dotNum = 0;
pause(0.1);
try
[str,count,msg] = fgetl(serialPort);
disp(str);
% str = fgetl(serialPort);
catch
disp('1\n\r');
end
figure('Position',[20,500,550,400]);
hold on;
grid on;
grid minor;
while ischar(str)
while 1 ~= strcmp(strChecker,frameHead)
if iStr > dataBufferSize
try
[str,count,msg] = fgetl(serialPort);
disp(str);
catch
disp('2\n\r');
end
iStr = 1;
end
strChecker(1) = strChecker(2);
strChecker(2) = str(iStr);
iStr = iStr + 1;
end
if iStr > dataBufferSize
try
[str,count,msg] = fgetl(serialPort);
disp(str);
catch
disp('2\n\r');
end
iStr = 1;
end
data = str2double(str(iStr));
if 0 == isnan(data)
if data ~= 0
channelNum = data;
end
end
iStrBuf = 1;
iStr = iStr + 1;
while 1 ~= strcmp(strChecker,frameEnd)
if iStr > dataBufferSize
try
[str,count,msg] = fgetl(serialPort);
disp(str);
catch
disp('3\n\r');
end
iStr = 1;
end
if (str(iStr) >= '0' && str(iStr) <= '9') ...
|| str(iStr) == '-' || str(iStr) == '.'
if str(iStr) == '.'
dotNum = dotNum + 1;
end
strBuffer(iStrBuf) = str(iStr);
iStrBuf = iStrBuf + 1;
end
strChecker(1) = strChecker(2);
strChecker(2) = str(iStr);
iStr = iStr + 1;
end
% strBuffer(iStrBuf) = ' ';
if dotNum <= 1
dotNum = 0;
deblank(strBuffer);
data = str2double(strBuffer);
if 0 == isnan(data)
dispBuffer(channelNum,1) = data;
end
strBuffer = blanks(length(strBuffer));
dispBuffer(channelNum,:) = ...
[dispBuffer(channelNum,2:plotWinLength) dispBuffer(channelNum,1)];
if channelNum == 6
% clf;
tAxes = tAxes + 1;
x = tAxes : 1 : tAxes + plotWinLength - 1;
t = x ./ dataRate;
plot(t,dispBuffer(6,:),'color','b');
nonZeros = dispBuffer(6,logical(dispBuffer(6,:)));
axis([t(1) t(end) (min(nonZeros) * 0.9999) (max(nonZeros) * 1.0001)]);
title('实时采样电压');
ylabel('vol/V');
xlabel('time/s');
pause(0.0005);
end
else
dotNum = 0;
strBuffer = blanks(length(strBuffer));
end
end
fclose(serialPort);
delete(serialPort);
clear serialPorts;