-->

Matlab的从特定采样速率的串行端口读(Matlab reading from serial po

2019-10-29 05:17发布

我想从两个传感器(在我的Arduino)正在发送到串口,与下面的MATLAB代码读取值。 但是,它错误说??? Attempted to access sensor1(1); index out of bounds because numel(sensor1)=0 ??? Attempted to access sensor1(1); index out of bounds because numel(sensor1)=0 ??? 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);


}

Answer 1:

你可以试试你的fscanf语句之前使用这样的:

while(get(serial_port,'BytesToRead')<2) ; end

这将等到有串行数据缓冲区的两个字节你读它们之前。

PS:如果您要发送号码,你会过得更好把他们的数字,而不是作为一个字符串 - 你需要发送三个字节来表示101 - 每个数字 - 虽然这可以作为一个字节发送。 使用FWRITE和FREAD做到这一点在Matlab,Serial.write和Serial.read上的Arduino。



文章来源: Matlab reading from serial port at specific sampling rate