Matlab 以特定采样率从串口读取 [英] Matlab reading from serial port at specific sampling rate

查看:23
本文介绍了Matlab 以特定采样率从串口读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用下面的 matlab 代码从发送到串行端口的两个传感器(在我的 arduino 上)读取值.但是,它错误地说 ???试图访问sensor1(1);索引越界,因为 numel(sensor1)=0 并且如果没有发生错误,则结果不准确.我知道这一点,因为我只是将 1 和 2 作为传感器值发送到 com 端口,结果两个数组也包含一些零(当一个应该全为 1 而另一个全为 2 时).感谢任何帮助,将不胜感激.

I am trying to read values from two sensors (on my arduino) that are being sent to the serial port, with the matlab code below. However, it errors saying ??? Attempted to access sensor1(1); index out of bounds because numel(sensor1)=0 and if the error does not occur the results are not accurate. I know this because I simply sent 1 and 2 as the sensor values to the com port and the resulting two arrays contained some zeros too (when one should be all 1's and the other all 2's). Thanks any help will be greatly appreciated.

这是我的matlab代码:

Here is my matlab code:

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 代码:

this is my sending arduino code:

int sensor1=0;
int sensor2= 0;

void setup(){

  Serial.begin(115200);

}

void loop(){

  sensor1= 1;
  sensor2= 2;

  Serial.println(sensor1);
  Serial.println(sensor2);


}

推荐答案

您可以尝试在 fscanf 语句之前使用它:

You could try using this before your fscanf statements:

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

这将等到串行缓冲区中有两个字节时才读取它们.

This will wait until there are two bytes in the serial buffer before you read them.

PS:如果您要发送数字,最好将它们作为数字而不是字符串发送 - 您需要发送三个字节来表示 101 - 每个数字一个 - 而这可以作为单个字节发送.在 Matlab 中使用 fwrite 和 fread,在 Arduino 上使用 Serial.write 和 Serial.read.

PS: If you are sending numbers you would be better off sending them as numbers rather than as a string - you will need to send three bytes to represent 101 - one for each digit - while this can be sent as a single byte. Use fwrite and fread to do this in Matlab, Serial.write and Serial.read on Arduino.

这篇关于Matlab 以特定采样率从串口读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆