0
我正嘗試讀取兩個傳感器(在我的arduino上)發送到串口的數值,下面是matlab代碼。但是,它的錯誤說??? Attempted to access sensor1(1); index out of bounds because numel(sensor1)=0
,如果錯誤沒有發生,結果是不準確的。我知道這一點,因爲我只是將1和2作爲傳感器值發送到COM端口,結果兩個數組也包含一些零(當一個應該全是1而另一個全部爲2時)。感謝任何幫助將不勝感激。Matlab以特定採樣率從串口讀取數據
這裏是我的MATLAB代碼:
close all;
clc;
fs = 1000; % sampling frequency (samplings per second)
mt = 20; % time for measurements
ind = 1;
nind = 1;
%Open serial port
delete(instrfind({'Port'},{'/dev/tty.usbmodem641'}));
serial_port=serial('/dev/tty.usbmodem641');
serial_port.BaudRate=115200;
warning('off','MATLAB:serial:fscanf:unsuccessfulRead');
%Open serial port
fopen(serial_port);
pause(2);
%Declare sample count
sample_count=1;
tic;
while toc < mt
time(ind) = toc;
sensor1=fscanf(serial_port,'%d')';
sensor2=fscanf(serial_port,'%d')';
channel1(ind) = (sensor1(1));
channel2(ind) = (sensor2(1));
% wait for appropriate time for next measurement
while(nind == ind)
nind = floor(toc*fs) + 1;
end
ind = nind;
end
%close connection
fclose(serial_port);
delete(serial_port);
這是我送的Arduino代碼:
int sensor1=0;
int sensor2= 0;
void setup(){
Serial.begin(115200);
}
void loop(){
sensor1= 1;
sensor2= 2;
Serial.println(sensor1);
Serial.println(sensor2);
}