我正在尝试从发送到串行端口的两个传感器(在我的 arduino 上)读取值,下面的 matlab 代码。但是,它会出错??? Attempted to access sensor1(1); index out of bounds because numel(sensor1)=0
,如果没有发生错误,则结果不准确。我知道这一点,因为我只是将 1 和 2 作为传感器值发送到 com 端口,结果两个数组也包含一些零(当一个应该全为 1 而另一个全为 2 时)。感谢任何帮助将不胜感激。
这是我的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);
}